Why dual __init__ in python?
inheritance, oop, python, super
Solution
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.
Problem
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) ```