How does single inheritance work in Python, and how do you use `super()`?
Single inheritance means a class inherits from one parent class. The child class gets all attributes and methods of the parent and can override or extend them.
super() returns a proxy object that delegates method calls to the parent class in the MRO. In Python 3, super() with no arguments automatically detects the class and instance. It's preferred over directly calling Parent.method(self) because it works correctly with multiple inheritance and cooperative method chains.
Key behaviors:
- The child inherits all methods and attributes from the parent
- The child can override methods by defining them with the same name
super().__init__()calls the parent's initializersuper()follows the MRO, not necessarily the direct parent
1. class Child(Parent): -- Child inherits from Parent
2. super().__init__() -- call parent's __init__
3. super().method() -- call parent's method
4. Override by redefining a method with the same name
5. Extend by calling super().method() then adding behavior
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def speak(self):
return f"{self.name} makes a sound"
def __repr__(self):
return f"{self.__class__.__name__}({self.name!r})"
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name, species="Canine")
self.breed = breed
def speak(self): # override
return f"{self.name} says Woof!"
def fetch(self): # new method
return f"{self.name} fetches the ball"
class GuideDog(Dog):
def __init__(self, name, breed, handler):
super().__init__(name, breed) # calls Dog.__init__
self.handler = handler
def speak(self): # extend parent method
base = super().speak() # calls Dog.speak()
return f"{base} (quietly)"
# Usage
dog = Dog("Rex", "Shepherd")
print(dog.speak()) # Rex says Woof!
print(dog.species) # Canine (inherited from Animal)
print(dog.fetch()) # Rex fetches the ball
guide = GuideDog("Buddy", "Labrador", "Alice")
print(guide.speak()) # Buddy says Woof! (quietly)
print(guide.handler) # Alice
print(guide.species) # Canine (inherited through chain)
# isinstance checks
print(isinstance(guide, GuideDog)) # True
print(isinstance(guide, Dog)) # True
print(isinstance(guide, Animal)) # True
# super() is equivalent to:
# super(GuideDog, self) in Python 3
# It follows MRO, not just direct parent
print(GuideDog.__mro__)
# (GuideDog, Dog, Animal, object)
- •Child inherits all attributes and methods from parent
- •super() delegates to the next class in the MRO
- •Override by redefining; extend by calling super() first
- •super() with no args auto-detects class and instance in Python 3
- •Forgetting super().__init__() means parent attributes are never set
- •super() follows MRO, which may not be the direct parent in multiple inheritance
- •Parent.__init__(self) works but breaks cooperative multiple inheritance