I have one question: if I want to access a parent class property, do I need to define super, or can I access it directly using self?
If the parent constructor is already being called, then:
-
β you donβt need
super()just to access parent property -
β you can simply use
self.property_nameanywhere in child class
π§ Suppose this:
class BankAccount:
def __init__(self):
self.bank_name = "SBI"
def show_bank(self):
print(f"This is {self.bank_name}")
class SavingsAccount(BankAccount):
def show_details(self):
print(self.bank_name) # β
parent property
self.show_bank() # β
parent method
β
This will work perfectly because SavingsAccount didn't override the parent constructor because in a child we didnβt create any child class constructor
β So Python automatically called the parent one
acc = SavingsAccount()
acc.show_details()
β οΈ but if you override constructor:
class SavingsAccount(BankAccount):
def __init__(self):
self.type = "Savings"
Now when you do:
acc = SavingsAccount()
print(acc.bank_name)
β It will give error β AttributeError: 'SavingsAccount' object has no attribute 'bank_name'
Why?
β Because you wrote your own constructor, so Python skipped the parent one
β And you didnβt call super().__init__()
β Fix it like this:
class SavingsAccount(BankAccount):
def __init__(self):
super().__init__() # brings bank_name
self.type = "Savings"
Now:
print(self.bank_name) # β
works
So summary:
-
If no child constructor β parent constructor auto-called β you can use self
-
If child has its own constructor β use
super().__init__()to bring parent things