2014-09-29 70 views
0

我已经看到下面的代码:继承查询在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() 

    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 

我不明白,为什么下面的代码输出Summoning Charm Accio No description。我很困惑为什么打印No description

spell = Accio() 
print spell 

谢谢

+1

它的代码应该有“子类”,或缩进怪异? – matsjoyce 2014-09-29 17:49:25

回答

1

__str__函数在构建时调用strprint语句与对象一起使用。当需要该类的实例的“非正式”字符串表示形式时使用它。 (from the docs)

两个简化多一点, print声明不能用于这样的对象作为对象的行为没有定义。 __str__定义了与print语句一起使用时对象的行为方式。

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

这里它打印的self.nameself.incantation其值是Summoning Charm Accio 它还调用返回No description从而使输出的self.get_description()

def get_description(self): 
     return 'No description' 
0

Spell.__str__()电话get_description(),但Accio不会覆盖get_description()

+0

虽然你的答案是正确的,但可能需要更多描述才能理解正在发生的事情。 – user3885927 2014-09-29 20:08:40