我正在用Python学习OOP,并且我正在iheritances类中训练多态性。
所以,我尝试了下面的代码:
class MaquinaBebida():
def __init__(self):
# Some self.methods
self.adicionarComplemento()
# Another self.methods
# Some methods
def adicionarComplemento(self):
print("Complemento adicionado.")
# Another methods
class MaquinaCha(MaquinaBebida):
def __init__(self, cond):
self.cond = cond
super().__init__()
def adicionarComplemento(self):
if self.cond:
print("Leite adicionado.")
print("MÁQUINA GERAL:\n\n\n\n")
geral = MaquinaBebida()
print("\n\n\n\nMÁQUINA CHÁ:\n\n\n\n")
cha = MaquinaCha(True)
这段代码运行良好。但是,如果我在 MaquinaCha 类构造函数中交换“self.cond”和“super().init()”的顺序,代码将无法工作,并且会抛出“AttributeError: 'MaquinaCha' object has没有属性“条件””。错误的代码,供比较:
# CODE
class MaquinaCha(MaquinaBebida):
def __init__(self, cond):
super().__init__()
self.cond = cond
def adicionarComplemento(self):
if self.cond:
print("Leite adicionado.")
# CODE
因此看来 super().init 之后的 wathever 语句不会被执行。 为什么会有这种行为?
我尝试在 super().init 之后添加一些变量声明,但也没有说什么。这些变量不会被解释。
类似的问题是here,但没有具体答案。
这是一个有趣的问题,通过查看执行顺序可能最容易回答这个问题。首先考虑以下几点:
class MaquinaBebida:
def __init__(self):
pass
#self.adicionarComplemento()
def adicionarComplemento(self):
print("Complemento adicionado.")
class MaquinaCha(MaquinaBebida):
def __init__(self, cond):
super().__init__()
self.cond = cond
def adicionarComplemento(self):
if self.cond:
print("Leite adicionado.")
geral = MaquinaBebida()
cha = MaquinaCha(True)
cha.adicionarComplemento()
我只是在第一个 init 中对这一行进行了哈希处理,我们看到它也成功了。
让我们看看有问题的行:
cha = MaquinaCha(True)
。
这会调用 MaquinaCha 的 __init__
方法。
接下来执行的是
super().__init__()
,它调用self.adicionarComplemento()
。
此时认识到 self 是什么很重要 - 它指的是最新的结构,在本例中是
MaquinaCha
的一个实例。这又调用了 adicionarComplemento 的新方法 - 在这里我们看到了错误。
新方法的第一行是
if self.cond
,但 self.cond 未定义,脚本失败。解决这个问题的一种方法如下:
class MaquinaBebida:
def __init__(self):
MaquinaBebida.adicionarComplemento()
@classmethod
def adicionarComplemento(cls):
print("Complemento adicionado.")
class MaquinaCha(MaquinaBebida):
def __init__(self, cond):
super().__init__()
self.cond = cond
def adicionarComplemento(self):
if self.cond:
print("Leite adicionado.")
geral = MaquinaBebida()
cha = MaquinaCha(True)