Lesson explanation
super()After this lesson, you will be able to:
super().__init__(...) to initialize inherited instance state before adding new attributes.super().method(...) instead of copying its logic.Inheritance lets one class reuse the behavior of another. Put the parent class in parentheses:
class Job:
pass
class SpecialJob(Job):
passA subclass inherits accessible methods and attributes from its parent. It can also define its own attributes and methods. When the subclass defines an __init__, the parent's initializer is not automatically called. Call super().__init__(...) to establish the parent's attributes before adding new ones.
The super() helper also lets an overriding instance method call the parent's implementation. That avoids duplicating a working base behavior. The next lesson will focus on method overriding and polymorphism in depth; for now, use an override only when it needs to extend what the parent already does.
A subclass can call a parent method even when it does not define that method itself.
class Device:
def __init__(self, identifier):
self.identifier = identifier
def label(self):
return f"Device {self.identifier}"
class Laptop(Device):
pass
print(Laptop("A14").label())Output:
Device A14Laptop inherited the label() method from Device.
Use super().__init__ to keep the parent's setup intact.
class Account:
def __init__(self, owner):
self.owner = owner
class PremiumAccount(Account):
def __init__(self, owner, credits):
super().__init__(owner)
self.credits = credits
print(f"{PremiumAccount('Noor', 50).owner}: premium")Output:
Noor: premiumThe parent creates owner; the child adds credits.
super()The child can reuse a parent's result and append its own information.
class Message:
def __init__(self, text):
self.text = text
def summary(self):
return self.text
class UrgentMessage(Message):
def summary(self):
return f"URGENT: {super().summary()}"
print(UrgentMessage("Restart required").summary())Output:
URGENT: Restart requiredThe overridden method calls the parent's method, rather than rewriting its behavior.
Inherited methods can be called on different subclasses or parent instances.
class Counter:
def __init__(self, value):
self.value = value
def double(self):
return self.value * 2
class LabeledCounter(Counter):
def __init__(self, value, label):
super().__init__(value)
self.label = label
print(LabeledCounter(7, "items").double())Output:
14The subclass adds label without losing the parent's double() method.
| Goal | Python |
|---|---|
| Inherit from a parent | class Child(Parent): |
| Run parent's initializer | super().__init__(...) |
| Extend a parent method | super().method(...) |
| Keep parent behavior unchanged | Do not redefine that method |
__init__ but forgetting to initialize parent attributes.self manually to super().__init__.super().