python中的类需要guidan

2024-10-04 11:29:04 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面代码的最后一行:studySpell(Confundo() 函数studySpellConfundo类的一个新实例赋给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

如果你不明白我的意思,让我知道我会尽量多说教。你知道吗


Tags: nameselfreturninitdefclassprintcharm
2条回答

要实现所需的功能,必须重新分配变量,然后执行以下方法:

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

你的代码,正如你所发布的,正在正常工作。你知道吗

studySpell函数不“赋值”给spell变量(全局变量)。它创建了一个新的局部变量(也称为spell),该变量隐藏了全局spell变量,并在函数执行完毕后消失。你知道吗

相关问题 更多 >