super
In Python classes, super() is used to call a method from a parent (or superclass), often in inheritance.
🔹 Use of super()
class Dog(Animal):
def speak(self):
super().speak() # Calls Animal's speak()
print("Dog barks") # Adds to it
Output:
Animal speaks
Dog barks
🔹 Example: Setting a Parent Attribute in Child
class Parent:
def __init__(self):
self.value = 10
class Child(Parent):
def __init__(self):
super().__init__()
self.value = 20 # modifies parent's 'value' attribute
c = Child()
print(c.value) # Output: 20
You're not modifying the parent class itself, but the instance created from it. Since the child inherits from the parent, it can access and change instance attributes.
🔹 Adding New Attributes in Child
class Child(Parent):
def __init__(self):
super().__init__()
self.new_attr = 99 # totally new attribute
✔️ Totally valid — child instances can have more attributes than the parent.
Want an example with method override or attribute shadowing?
Key Points:
-
super()gives you access to methods from the parent class without hardcoding the parent’s name. -
It's mostly used in
__init__, but works with any method. -
It respects the method resolution order (MRO), important for multiple inheritance.
Let me know if you want a quick example with multiple inheritance.
Tags: #programming #tools