我正在研究pythonoop风格。我把__init__
的构造方法如下。我以前没见过这种款式。为什么在这篇文章中使用双__init__
方法?在
前-
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)
这只不过是伪装地调用
ParentClass.__init__()
,也就是说首选的Python样式是显式地使用super,而不是在父类的名称中使用硬代码。在
(在python3.x中:可以说
super().__init__()
)所以这实际上只是伪装的Understanding Python super() with init() methods;这里,ChildClass是最小余额账户
类
MinimumBalanceAccount
派生自类BankAccount
。因此,在类的init函数中,它需要调用基类的init,这是由BankAccount.__init__(self)
完成的。在这是Python中类继承的一个例子。您已将
BankAccount
类继承到MinimumBalanceAccount
类。但是,通过在MinimumBalanceAccount
类中引入__init__
函数,您已经重写了BankAccount
类的__init__
函数。基类可能会初始化一些您需要的变量。因此在子类'__init__
构造函数中调用它以确保。在您可以使用
super
类来实现相同的行为。 在python2.x中,等效的或者在python3.x中
^{pr2}$但是,您必须明白,它只会运行它首先从基方法中找到的
__init__
方法。因此,就多重继承而言,如果基类中没有实现super
,则很难调用其他各种类的__init__
方法。所以请避免不惜一切代价使用多重继承,或者在所有类中实现super
。在如果您仍然希望进行多重继承,最好使用
ParentClass.__init__
方法,或者在所有基类中添加对__init__
的super
方法调用。在相关问题 更多 >
编程相关推荐