- Explain the ideas of a class and an object
- Write a class with
__init__, attributes and methods - Use inheritance and override a method
You are writing a class register: every student has a name, a grade level and scores, and you need to add new scores and calculate averages. With 30 students, separate variables and functions quickly turn into a mess. Object-oriented programming (OOP) offers another way: bundle the data and the functions that work with it into one package — an object.
Class and object
A class is a blueprint for objects: it describes what data each object will have and what it can do. An object is a concrete instance built from that blueprint. Just as one blueprint can be used to build many houses, one class can create as many objects as you like.
| Term | Meaning | In the example |
|---|---|---|
| Class | the blueprint for objects | Student |
| Object | an instance made from a class | aysel |
| Attribute | a variable inside an object | self.name |
| Method | a function inside an object | average() |
Your first class
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
self.scores = []
def add_score(self, score):
self.scores.append(score)
def average(self):
return sum(self.scores) / len(self.scores)
def __str__(self):
return f'{self.name} (grade {self.grade})'
aysel = Student('Aysel', 8)
murad = Student('Murad', 9)
aysel.add_score(5)
aysel.add_score(4)
murad.add_score(3)
print(aysel, aysel.scores)
print(murad, murad.scores)
print('Average:', aysel.average())▸ Expected output
Aysel (grade 8) [5, 4] Murad (grade 9) [3] Average: 4.5
class Student:defines a new class. Class names usually start with a capital letter.__init__is a special method — the constructor: it is called automatically when you writeStudent('Aysel', 8)and sets up the object's attributes.selfis the object the method is called on. When you writeaysel.add_score(5),selfisaysel.__str__decides how the object looks when youprintit.
Notice that aysel and murad come from the same class, but each has its own list of scores. Adding a score to one does not affect the other — objects are independent.
Inheritance
Inheritance lets you create a new class based on an existing one. The child class receives all the attributes and methods of the parent class and can override the ones it needs to change. Below, Dog and Cat take the introduce method ready-made from Animal but replace speak with their own version:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return '...'
def introduce(self):
return f'I am {self.name} and I say {self.speak()}'
class Dog(Animal):
def speak(self):
return 'Woof!'
class Cat(Animal):
def speak(self):
return 'Meow!'
for pet in [Dog('Rex'), Cat('Mestan'), Animal('Nemo')]:
print(pet.introduce())▸ Expected output
I am Rex and I say Woof! I am Mestan and I say Meow! I am Nemo and I say ...
The same introduce() call gave a different result for each object, because each object uses its own speak method. This is called polymorphism. If a child class needs a new attribute, its __init__ first calls the parent's constructor with super().__init__(...):
class Animal:
def __init__(self, name):
self.name = name
class Parrot(Animal):
def __init__(self, name, words):
super().__init__(name)
self.words = words
def talk(self):
return self.name + ' says ' + ' and '.join(self.words)
tutu = Parrot('Tutu', ['hello', 'salam'])
print(tutu.talk())
print(isinstance(tutu, Animal))▸ Expected output
Tutu says hello and salam True
Write a class Player: __init__ stores the name and sets score to 0, the method add_points(points) increases the score, and __str__ returns text like Aysel: 25 points. The lower part of the starter code tests the class — do not change it.
class Player:
# __init__(self, name): save the name, set score to 0
# add_points(self, points): add points to score
# __str__(self): return text like Aysel: 25 points
pass
aysel = Player('Aysel')
murad = Player('Murad')
aysel.add_points(10)
aysel.add_points(15)
murad.add_points(20)
print(aysel)
print(murad)▸ Expected output
Aysel: 25 points Murad: 20 points
The class Shape is ready. Derive two subclasses from it: Square (with a side) and Rectangle (with width and height). Each should pass its name ('Square', 'Rectangle') through super().__init__() and define its own area() method. Then print the result of describe() for Square(4) and Rectangle(5, 3).
class Shape:
def __init__(self, name):
self.name = name
def area(self):
return 0
def describe(self):
return f'{self.name}: area {self.area()}'
# 1) class Square(Shape) with side; area = side * side
# 2) class Rectangle(Shape) with width and height
# 3) print describe() for Square(4) and Rectangle(5, 3)▸ Expected output
Square: area 16 Rectangle: area 15
Key points
- A class is a blueprint; an object is a concrete instance of it.
__init__runs automatically when an object is created and sets up its attributes.- The first parameter of a method is
self— the object the method is called on. class Dog(Animal):is inheritance:Doggets everything from its parent and can override methods.super().__init__()calls the parent's constructor from a child class.
Check yourself
10 questions. Every correct answer earns XP.