Python · Classes and OOP
Quizz
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — What is self?
In a class method, what does `self` refer to?
Options
• The class itself
• The current instance of the class
• The parent class
• A global variable
Hint : Think about what object is calling the method. `self` is the specific object, not the blueprint.
Exercise 2 — Object Creation Output
What does this code print?
class Codemon:
def __init__(self, name):
self.name = name
print(f"{name} appears!")
myCdm = Codemon("Aquachu")
Options
• Nothing
• `Aquachu appears!`
• `Codemon appears!`
• Error
Hint : `__init__` is called automatically when you create an object. What is the value of `name` here?
Exercise 3 — Role of __init__
What is the purpose of the `__init__` method in a class?
Options
• To delete an object
• To initialize the attributes when creating an object
• To print the object
• To import a module
Hint : The name `__init__` comes from "initialize". It runs once, right when the object is born.
Exercise 4 — Default Parameter Behavior
What does this code print?
class Codemon:
def __init__(self, name, level=1):
self.name = name
self.level = level
myCdm = Codemon("Pyrochu")
print(myCdm.level)
Options
• `None`
• `0`
• `1`
• Error: missing argument
Hint : When a parameter has a default value like `level=1`, you don't need to provide it. What value will it have?
Exercise 5 — What Does Inheritance Give You?
What is the main benefit of inheritance in OOP?
Options
• It makes your code run faster
• It lets a class reuse the attributes and methods of another class
• It prevents bugs
• It encrypts the data
Hint : Think about what a child class "inherits" from its parent. It's about reusing existing code.
Exercise 6 — What Does super() Do?
What does `super().__init__(name)` do in a child class?
class Codemon:
def __init__(self, name):
self.name = name
class WaterCodemon(Codemon):
def __init__(self, name, swim_speed):
super().__init__(name)
self.swim_speed = swim_speed
Options
• It creates a new parent object
• It calls the parent class's `__init__` to set up `name`
• It deletes the parent class
• It skips the parent's initialization
Hint : `super()` gives you access to the parent class. So `super().__init__()` calls the parent's constructor.
Exercise 7 — Method Overriding
What does this code print?
class Codemon:
def cry(self):
return "Roar!"
class Aquachu(Codemon):
def cry(self):
return "Splash!"
myCdm = Aquachu()
print(myCdm.cry())
Options
• `Roar!`
• `Splash!`
• `Roar! Splash!`
• Error
Hint : When a child class defines a method with the same name as the parent, the child's version takes priority.
Exercise 8 — Private Attribute Convention
In Python, what does naming an attribute with an underscore prefix like `_hp` mean?
Options
• The attribute is completely inaccessible from outside
• The attribute is encrypted
• It's a convention that signals the attribute is private and shouldn't be accessed directly
• It makes the attribute read-only
Hint : Python doesn't truly enforce private attributes. The underscore is a signal to other developers.
Exercise 9 — What Does a Getter Do?
What is the purpose of a getter method in a class?
class Codemon:
def __init__(self, name, hp):
self._hp = hp
def get_hp(self):
return self._hp
Options
• To modify a private attribute
• To safely read a private attribute without exposing it directly
• To delete a private attribute
• To create a new attribute
Hint : A getter "gets" a value. It provides controlled access to a private attribute.
Exercise 10 — What Does __str__ Return?
What does this code print?
class Codemon:
def __init__(self, name, level):
self.name = name
self.level = level
def __str__(self):
return f"{self.name} Lv.{self.level}"
myCdm = Codemon("Florachu", 5)
print(myCdm)
Options
• `<__main__.Codemon object at 0x...>`
• `Florachu Lv.5`
• `Codemon Lv.5`
• Error
Hint : `__str__` is called automatically by `print()`. It returns a human-readable string representation of the object.
Exercise 11 — What Does __eq__ Control?
What does defining `__eq__` in a class allow you to control?
Options
• How objects are printed
• How objects are compared with `==`
• How objects are sorted
• How objects are created
Hint : The `eq` in `__eq__` stands for "equals". Think about which operator tests equality.
Exercise 12 — What Does __len__ Enable?
What does this code print?
class Team:
def __init__(self):
self.members = ["Aquachu", "Pyrochu"]
def __len__(self):
return len(self.members)
t = Team()
print(len(t))
Options
• Error: `len()` doesn't work on custom objects
• `2`
• `0`
• `None`
Hint : `__len__` makes `len()` work on your custom objects. How many members are in the list?
Exercise 13 — What Does __lt__ Enable?
If you define `__lt__` in your class, which operation becomes possible?
Options
• Using `+` between two objects
• Using `<` to compare two objects
• Using `len()` on an object
• Using `print()` on an object
Hint : `lt` stands for "less than". Each special method maps to a specific operator.
Exercise 14 — What is Composition?
What does composition mean in OOP?
Options
• A class inherits from another class
• A class contains objects of other classes as attributes
• Two classes share the same methods
• A class is defined inside another class
Hint : Composition is a "has-a" relationship. A Team "has" Codémon, rather than "is a" Codémon.
Exercise 15 — Object Type
What does `type(myCdm)` return when `myCdm = Codemon("Aquachu")`?
class Codemon:
def __init__(self, name):
self.name = name
myCdm = Codemon("Aquachu")
print(type(myCdm))
Options
• `<class 'str'>`
• `<class 'Codemon'>`
• `<class 'object'>`
• `Codemon`
Hint : `type()` returns the class of an object. The object was created from the `Codemon` class.
Exercise 16 — Complete a Class Definition
Complete the class definition for a Codémon.
____ Codemon:
def __init__(self, name):
self.name = name
myCdm = Codemon("Aquachu")
print(myCdm.name)
Options: class def object new
Hint : What keyword do you use to define a new class in Python?
Exercise 17 — Complete __init__
Complete the constructor so each Codémon has a `name` and `element`.
class Codemon:
def __init__(self, name, element):
self.name = name
self.____ = ____
myCdm = Codemon("Pyrochu", "Fire")
print(myCdm.element)
Options: element name self type element name self type
Hint : You need to store the `element` parameter as an attribute of the object using `self`.
Exercise 18 — Complete a Method Call
Complete the code so the Codémon levels up and we print the new level.
class Codemon:
def __init__(self, name, level=1):
self.name = name
self.level = level
def level_up(self):
self.level += 1
myCdm = Codemon("Florachu")
myCdm.____()
print(myCdm.____)
Options: level_up level name __init__
Hint : First call the method that increases the level, then access the attribute that stores it.
Exercise 19 — Complete Inheritance Syntax
Complete the code so `WaterCodemon` inherits from `Codemon`.
class Codemon:
def __init__(self, name):
self.name = name
def cry(self):
return "Roar!"
class WaterCodemon(____):
pass
myCdm = WaterCodemon("Aquachu")
print(myCdm.cry())
Options: Codemon self object WaterCodemon
Hint : To inherit from a class, put the parent class name inside the parentheses after the child class name.
Exercise 20 — Complete super() Call
Complete the child class so it properly initializes the parent's `name` attribute.
class Codemon:
def __init__(self, name):
self.name = name
class FireCodemon(Codemon):
def __init__(self, name, temperature):
____().__init__(name)
self.temperature = temperature
myCdm = FireCodemon("Pyrochu", 800)
print(myCdm.name, myCdm.temperature)
Options: super self Codemon parent
Hint : Which built-in function gives you access to the parent class from inside a child class?
Exercise 21 — Complete __str__
Complete the method's name so `print(myCdm)` displays `Aquachu - 100HP`.
class Codemon:
def __init__(self, name, hp=100):
self.name = name
self.hp = hp
def ____(self):
return f"{self.name} - {self.hp}HP"
myCdm = Codemon("Aquachu")
print(myCdm)
Options: __str__ __init__ __repr__ display
Hint : Which special method does `print()` call to get a string representation of an object?
Exercise 22 — Output Prediction: Inheritance
What does this code print?
class Codemon:
def __init__(self, name, hp=100):
self.name = name
self.hp = hp
class EliteCodemon(Codemon):
def __init__(self, name):
super().__init__(name, 200)
myCdm = EliteCodemon("Metachu")
print(myCdm.hp)
Options
• `100`
• `200`
• `None`
• Error
Hint : The child class calls `super().__init__(name, 200)`. What value does the parent receive for `hp`?
Exercise 23 — Calling Parent Methods
Can a child class call a method defined in its parent class?
class Codemon:
def cry(self):
return "Roar!"
class Aquachu(Codemon):
pass
myCdm = Aquachu()
print(myCdm.cry())
Options
• No, it causes an error
• Yes, it prints `Roar!`
• Yes, but it prints `None`
• Only if you use `super().cry()`
Hint : Inheritance means the child class gets all methods from the parent. Can the child use them directly?
Exercise 24 — Setter Validation
Complete the setter so HP can never go below 0.
class Codemon:
def __init__(self, name, hp=100):
self.name = name
self._hp = hp
def set_hp(self, value):
self._hp = ____(0, value)
def get_hp(self):
return self._hp
myCdm = Codemon("Rockachu")
myCdm.set_hp(-50)
print(myCdm.get_hp())
Options: max min abs int
Hint : You want the bigger value between 0 and the given value. Which function returns the larger of two numbers?
Exercise 25 — Composition Access Pattern
Complete the code to access the move's power through the Codémon object.
class Move:
def __init__(self, name, power):
self.name = name
self.power = power
class Codemon:
def __init__(self, name, move):
self.name = name
self.move = move
flame = Move("Flame Burst", 40)
myCdm = Codemon("Pyrochu", flame)
print(myCdm.____.____)
Options: move power name flame
Hint : First access the Codémon's `move` attribute, then chain to the Move's `power` attribute.
Back to the course