python - 为什么在 python 中使用 dual __init__?

标签 python oop inheritance super

我正在研究 python oop 风格。我似乎 __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)

最佳答案

这是Python中类继承的一个例子。您已将 BankAccount 类继承到 MinimumBalanceAccount 类。但是,通过在 MinimumBalanceAccount 类中引入 __init__ 函数,您已经覆盖了 BankAccount 类的 __init__ 函数。基类可能会初始化一些您需要的变量。因此它在 Child 类的 __init__ 构造函数中被调用以确保这一点。

您可以使用 super 类来实现相同的行为。 在 Python 2.x 中,等价物是

class MinimumBalanceAccount(BankAccount):
    def __init__(self, minimum_balance):
        self.minimum_balance = minimum_balance
        super(MinimumBalanceAccount, self).__init__()

或者在 Python 3.x 中,

class MinimumBalanceAccount(BankAccount):
    def __init__(self, minimum_balance):
        super().__init__()

但是,您必须明白,这只会运行它首先从基本方法中找到的任何 __init__ 方法。所以在多重继承方面,如果基类中没有实现super,调用其他各种类的__init__方法会很困难。因此,请不惜一切代价避免使用多重继承或在所有类中实现 super

(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

如果您仍然希望使用多重继承,最好使用 ParentClass.__init__ 方法或将 super 方法调用添加到 __init__在所有基类中。

关于python - 为什么在 python 中使用 dual __init__?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28544469/

相关文章:

python - Django 管理员 : Get logged In users id in django

python - 将 pyLDAvis 图导出为 pdf

php - 在这种情况下是使用接口(interface)还是抽象类更好?

javascript - 两个 javascript 函数,第二个函数等待第一个函数使用 getScript 从外部 URL 检索值

python - 如何用Python制作动态网格

python - 如何使用正则表达式在 Python 3 中的特定字符串之后或之前找到一行?

python - 从静态方法访问静态变量

c# - C#或者底层的CLR真的不支持多重继承吗?

c++ - 如何避免来自继承的属性冗余

c++ - 构造函数链接不使用类成员的默认值?