Sub topic 2
Initializing Parent State with `super().__init__()`
Assume you know how to define classes, create instances, write methods, and use function arguments. This chapter focuses on how subclasses initialize inherited state and how Python uses subclass relationships.
Initializing parent state with `super().__init__()`
A subclass is a class that inherits from another class. If the subclass does not define __init__(), Python uses the parent class's initializer. If it defines its own __init__(), the subclass must call the parent initializer explicitly when it needs the parent's attributes.
super() returns a proxy for the next class in the inheritance chain. Calling super().__init__() runs that class's initializer.
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
dog = Dog("Rex", "Labrador")
print(dog.name)
print(dog.breed)Without super().__init__(name), dog.name would not exist. The subclass initializer would replace the parent initializer instead of extending it.
Checking types with `isinstance()` and `issubclass()`
Use isinstance(object, Class) to test whether an object belongs to a class or one of its parent classes. Use issubclass(Child, Parent) to test the relationship between two classes.
class Animal:
pass
class Dog(Animal):
pass
dog = Dog()
print(isinstance(dog, Dog)) # True
print(isinstance(dog, Animal)) # True
print(issubclass(Dog, Animal)) # True
print(type(dog) is Animal) # FalsePrefer isinstance() when checking an object. It supports inheritance and therefore keeps code flexible.
Polymorphism: one call, many behaviors
Polymorphism means that one operation can work with objects of different subclasses. The caller depends on a shared method, while each subclass provides its own behavior.
class Animal:
def speak(self):
return "Some sound"
class Dog(Animal):
def speak(self):
return "Bark"
class Cat(Animal):
def speak(self):
return "Meow"
def announce(animal):
print(animal.speak())
for animal in [Dog(), Cat()]:
announce(animal)announce() does not check the exact type. It calls speak() on any object that provides the expected behavior.
Exercise
What is missing if a subclass defines __init__() but instances do not have an attribute created by the parent?
Show answer
The subclass likely needs to call super().__init__() so the parent can initialize that attribute.