2017-07-15 55 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 

你的代碼,你貼出來,正在工作,應該的。