在以下代码的第二行中:studySpell(Confundo()
其中函数studySpell
通过将Confundo
类指定给spell
来创建一个新实例。我的问题是,在执行第二行到最后一行之后,为什么spell.incantation
返回'Accio'
?它不应该返回'Confundo'
?python中的类需要指导
class Spell(object):
def __init__(self, incantation, name):
self.name = name
self.incantation = incantation
def __str__(self):
return self.name + ' ' + self.incantation + '\n' + self.getDescription()
def getDescription(self):
return 'No description'
def execute(self):
print(self.incantation)
class Accio(Spell):
def __init__(self):
Spell.__init__(self, 'Accio', 'Summoning Charm')
class Confundo(Spell):
def __init__(self):
Spell.__init__(self, 'Confundo', 'Confundus Charm')
def getDescription(self):
return 'Causes the victim to become confused and befuddled.'
def studySpell(spell):
print(spell)
>>> spell = Accio()
>>> spell.execute()
Accio
>>> studySpell(spell)
Summoning Charm Accio
No description
>>> studySpell(Confundo())
Confundus Charm Confundo
Causes the victim to become confused and befuddled.
>>> print(spell.incantation)
Accio
如果你不明白我的意思,让我知道我会尽力传讲更多。
为什么你认为调用'studySpell()'会改变'spell'实例? 'spell'仍然是'Accio'的一个实例。 – AChampion
尽管这里没有什么区别,但通常会使用'super()'来调用基类ctors(如果您有钻石继承模式,它将会有所不同)。 – thebjorn