python中的类需要指导

python中的类需要指导,python,Python,在下面代码的最后一行:studySpell(Confundo() 在哪个函数中,studySpell通过将Confundo类分配给spell来创建一个新实例。我的问题是,在执行倒数第二行之后,为什么拼写。咒语返回'Accio'?它不应该返回'Confundo' class Spell(object): def __init__(self, incantation, name): self.name = name self.incantation = inc

在下面代码的最后一行:
studySpell(Confundo()
在哪个函数中,
studySpell
通过将
Confundo
类分配给
spell
来创建一个新实例。我的问题是,在执行倒数第二行之后,
为什么拼写。咒语
返回
'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
函数不会“分配”到
拼写变量(全局变量)。它会创建一个新的局部变量(也称为
拼写
)这会使全局
拼写
变量变暗,并在函数执行完毕后消失。

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

要实现所需,必须重新分配变量,然后执行该方法:

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


正如您所发布的,您的代码正在正常工作。

要实现您想要的,您必须重新分配变量,然后执行该方法:

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


您发布的代码正常工作。

为什么您认为调用
studySpell()
会更改
拼写实例?
spell
仍然是
Accio
的一个实例。虽然在这里没有任何区别,但您通常会使用
super()
调用基类构造函数(如果你有菱形继承模式,这会有所不同。)为什么你认为调用
studySpell()
会改变
拼写
实例?
spell
仍然是
Accio
的一个实例。虽然在这里没有任何区别,但你通常会使用
super()
调用基类构造函数(如果你有钻石继承模式,那会有所不同。)35;比约恩哦,我知道了,非常感谢。我没想到会这样。#比约恩哦,我知道了,非常感谢。我没想到会这样。