2017-07-15 56 views
1

在以下代码的第二行中: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 

如果你不明白我的意思,让我知道我会尽力传讲更多。

+0

为什么你认为调用'studySpell()'会改变'spell'实例? 'spell'仍然是'Accio'的一个实例。 – AChampion

+0

尽管这里没有什么区别,但通常会使用'super()'来调用基类ctors(如果您有钻石继承模式,它将会有所不同)。 – thebjorn

回答

0

studySpell函数不会“分配”到spell变量(全局函数)。它会创建一个新的局部变量(也称为spell),它影响全局变量spell,并在函数执行完毕后消失。

+0

#thebjorn ohh我知道,非常感谢。我看不到即将到来的。 –

0

达到你想要什么,你不得不重新分配的变量,然后执行方法:

spell = Accio() 
spell.execute() 
studySpell(spell) 
studySpell(Confundo()) 
spell = Confundo() 
print(spell.incantation) 

Accio 
Summoning Charm Accio 
No description 
Confundus Charm Confundo 
Causes the victim to become confused and befuddled. 
Confundo 

你的代码,你贴出来,正在工作,应该的。