Python中的继承查询

Python中的继承查询,python,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.get_description() d

我看到了以下代码:

class Spell(object):
    def __init__(self, incantation, name):
        self.name = name
        self.incantation = incantation

    def __str__(self):
        return self.name + ' ' + self.incantation + '\n' + self.get_description()

    def get_description(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 get_description(self):
        return 'Causes the victim to become confused and befuddled.'


    def study_spell(spell):
        print spell
我不明白为什么下面的代码输出
召唤咒语Accio
无说明
。我不明白为什么要打印
没有说明

spell = Accio()
print spell

谢谢

拼写。
调用
get\u description()
,但是
Accio
不会覆盖
get\u description()
在对象中使用inbuild
str
print
语句时调用函数。当需要该类实例的“非正式”字符串表示形式时,使用它

再简单一点,
print
语句不能与对象一起使用,因为对象的行为未定义<代码>\uuuu str\uuuu
定义对象在与
print
语句一起使用时的行为方式

def __str__(self):
        return self.name + ' ' + self.incantation + '\n' + self.get_description()
这里它打印了
self.name
self.magntation
的值,它们是
召唤咒语Accio
它还调用
self.get_description()
,返回
No description
,从而给出输出

def get_description(self):
        return 'No description'

这可能是因为代码应该有“子类”,或者缩进很奇怪吗?虽然您的答案是正确的,但可能需要更多的描述来理解发生了什么。