在下面代码的最后一行:studySpell(Confundo()
函数studySpell
将Confundo
类的一个新实例赋给spell
。我的问题是,在执行从第二行到最后一行之后,spell.incantation
为什么返回'Accio'
?它不应该返回'Confundo'
吗?你知道吗
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
),该变量隐藏了全局spell
变量,并在函数执行完毕后消失。你知道吗相关问题 更多 >
编程相关推荐