Reputation: 443
I am investigating python oop style. I have seemed __init__
construction method as below. I did't see this style before. Why use dual __init__
methods as in this stuff?
ex-
class MinimumBalanceAccount(BankAccount):
def __init__(self, minimum_balance):
BankAccount.__init__(self)
self.minimum_balance = minimum_balance
def withdraw(self, amount):
if self.balance - amount < self.minimum_balance:
print 'Sorry, minimum balance must be maintained.'
else:
BankAccount.withdraw(self, amount)
Upvotes: 3
Views: 301
Reputation: 4250
This is an example of Class inheritance in Python. You have inherited the BankAccount
Class to the MinimumBalanceAccount
Class. However, by introducing an __init__
function in the MinimumBalanceAccount
Class, you have overridden __init__
function of BankAccount
Class. The base class might initialize some variables that are required for you. And hence it is called in the Child class' __init__
constructor to ensure that.
You can use super
class to implement the same behavior.
In Python 2.x, the equivalent will be
class MinimumBalanceAccount(BankAccount):
def __init__(self, minimum_balance):
self.minimum_balance = minimum_balance
super(MinimumBalanceAccount, self).__init__()
Or in Python 3.x,
class MinimumBalanceAccount(BankAccount):
def __init__(self, minimum_balance):
super().__init__()
However, you must understand that this will just run whatever __init__
method it finds first from the base methods. So in terms of multiple inheritance, it would be difficult to call __init__
methods of various other classes, if super
is not implemented in the base classes. So please avoid using multiple inheritance at all costs or implement super
in all classes.
(eg)
class BankAccount(object):
def __init__(self):
# Some action here
# But no super method called here
class MinimumBalanceAccount(BankAccount, LoanAccount):
def __init__(self, minimum_value):
super(MinimumBalanceAccount, self).__init__() # Calls BankAccount.__init__()
super(MinimumBalanceAccount, self).__init__() # Still calls the same
If you still wish to go for Multiple Inheritance, best go with the ParentClass.__init__
approach or add the super
method call to __init__
in all the base classes.
Upvotes: 5
Reputation: 33940
This is nothing more than calling ParentClass.__init__()
in disguise, i.e.
super(ChildClass, self).__init__()
The preferred Python style is to explicitly use super, rather than hardcode in the name of the parent class.
(In Python 3.x: you can just say super().__init__()
)
So this is really just Understanding Python super() with init() methods in disguise; here, ChildClass is MinimumBalanceAccount
Upvotes: 1
Reputation: 842
The class MinimumBalanceAccount
derives from the class BankAccount
. Therefore, in the class' init function, it needs to call the init of the base class, which is done by BankAccount.__init__(self)
.
Upvotes: 1