6

关于 SO 的类似问题包括:this onethis。我还阅读了所有我能找到的在线文档,但我仍然很困惑。我会很感激你的帮助。

我想在我的 CastSpell 类 lumus 方法中使用 Wand 类 .wandtype 属性。但我不断收到错误“AttributeError:'CastSpell'对象没有属性'wandtype'。”

此代码有效:

class Wand(object):
    def __init__(self, wandtype, length):
        self.length = length 
        self.wandtype = wandtype

    def fulldesc(self):
        print "This is a %s wand and it is a %s long" % (self.wandtype, self.length) 

class CastSpell(object):
    def __init__(self, spell, thing):
        self.spell = spell 
        self.thing = thing

    def lumus(self):
        print "You cast the spell %s with your wand at %s" %(self.spell, self.thing) 

    def wingardium_leviosa(self): 
        print "You cast the levitation spell."

my_wand = Wand('Phoenix-feather', '12 inches') 
cast_spell = CastSpell('lumus', 'door') 
my_wand.fulldesc()  
cast_spell.lumus() 

这段代码,尝试继承,没有。

class Wand(object):
    def __init__(self, wandtype, length):
        self.length = length 
        self.wandtype = wandtype

    def fulldesc(self):
        print "This is a %s wand and it is a %s long" % (self.wandtype, self.length) 

class CastSpell(Wand):
    def __init__(self, spell, thing):
        self.spell = spell 
        self.thing = thing

    def lumus(self):
        print "You cast the spell %s with your %s wand at %s" %(self.spell, self.wandtype, self.thing)   #This line causes the AttributeError! 
        print "The room lights up."

    def wingardium_leviosa(self): 
        print "You cast the levitation spell."

my_wand = Wand('Phoenix-feather', '12 inches') 
cast_spell = CastSpell('lumus', 'door') 
my_wand.fulldesc()  
cast_spell.lumus() 

我试过使用 super() 方法无济于事。我非常感谢您帮助理解 a)为什么在这种情况下类继承不起作用,b)如何让它工作。

4

3 回答 3

8

简而言之,您Wand.__init__在继承自它的类中覆盖,因此CastSpell.wandtype永远不会在CastSpell. 除此之外,my_wand无法将信息传递到cast_spell中,因此您对继承的作用感到困惑。

不管你怎么做,你必须以某种方式通过lengthwandtypeCastSpell。一种方法是将它们直接包含到CastSpell.__init__

class CastSpell(Wand):
    def __init__(self, spell, thing, length, wandtype):
        self.spell = spell 
        self.thing = thing
        self.length = length
        self.wandtype = wandtype

另一种更通用的方法是将这两个传递给基类自己的__init__()

class CastSpell(Wand):
    def __init__(self, spell, thing, length, wandtype):
        self.spell = spell 
        self.thing = thing
        super(CastSpell, self).__init__(length, wandtype)

另一种方法是停止CastSpell继承Wand(是CastSpell一种Wand?或某种东西Wand?),而是让每个 Wand 能够在其中包含一些CastSpells:而不是“is-a”(aCastSpell是一种Wand),试试“has-a”(aWandSpells)。

这是拥有魔杖存储咒语的一种简单但不是很好的方法:

class Wand(object):
    def __init__(self, wandtype, length):
        self.length = length
        self.wandtype = wandtype
        self.spells = {} # Our container for spells. 
        # You can add directly too: my_wand.spells['accio'] = Spell("aguamenti", "fire")

    def fulldesc(self):
        print "This is a %s wand and it is a %s long" % (self.wandtype, self.length)

    def addspell(self, spell):
        self.spells[spell.name] = spell

    def cast(self, spellname):
        """Check if requested spell exists, then call its "cast" method if it does."""
        if spellname in self.spells: # Check existence by name
            spell = self.spells[spellname] # Retrieve spell that was added before, name it "spell"
            spell.cast(self.wandtype) # Call that spell's cast method, passing wandtype as argument
        else:
            print "This wand doesn't have the %s spell." % spellname
            print "Available spells:"
            print "\n".join(sorted(self.spells.keys()))


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

    def cast(self, wandtype=""):
        print "You cast the spell %s with your %s wand at %s." % (
               self.name, wandtype, self.target)
        if self.name == "lumus":
            print "The room lights up."
        elif self.name == "wingardium leviosa":
            print "You cast the levitation spell.",
            print "The %s starts to float!" % self.target

    def __repr__(self):
        return self.name

my_wand = Wand('Phoenix-feather', '12 inches')
lumus = Spell('lumus', 'door')
wingardium = Spell("wingardium leviosa", "enemy")

my_wand.fulldesc()
lumus.cast() # Not from a Wand! I.e., we're calling Spell.cast directly
print "\n\n"

my_wand.addspell(lumus) # Same as my_wand.spells["lumus"] = lumus
my_wand.addspell(wingardium)
print "\n\n"

my_wand.cast("lumus") # Same as my_wand.spells["lumus"].cast(my_wand.wandtype)
print "\n\n"
my_wand.cast("wingardium leviosa")
print "\n\n"
my_wand.cast("avada kadavra") # The check in Wand.cast fails, print spell list instead
print "\n\n"
于 2012-05-20T01:21:19.737 回答
1

您需要调用超类的 init 方法。否则,不会在当前 CastSpell 实例上设置 wandtype 和 length。

class CastSpell(Wand):
    def __init__(self, spell, thing):
        super(CastSpell, self).__init__(A, B) # A, B are your values for wandtype and length
        self.spell = spell 
        self.thing = thing

或者,您可以在 init 方法之外的对象上添加 wandtype 和 length 作为属性:

class Wand(object):
    wandtype = None
    length = None

然后,它们将始终可用(尽管在初始化之前它们的值为 None )。


但是,您确定 CastSpell 应该是 Wand 的子类吗?CastSpell 是一个动作,听起来更像是 Wand 的一种方法。

class Wand(object):
    [...]
    def cast_spell(self, spell, thing):
         [etc.]
于 2012-05-20T01:20:54.150 回答
1

是的,super()不是你想要的。有关为什么不这样做的详细信息,请参阅本文

在 Python 中对超类的正常调用(不幸的是)是通过引用超类显式完成的。

如果我正确地解释了您的问题,您想知道为什么.length.wandtype属性没有出现在CastSpell. 这是因为魔杖。init () 方法没有被调用。你应该这样做:

class CastSpell(Wand):
    def __init__(self, spell, thing):
        Wand.__init__(self, whateverdefaultvalue_youwantforwandtype, default_value_for_length)
        self.spell = spell
        etc.

也就是说,您似乎没有正确使用继承。CastSpell 是一个“动作”,而 wand 是一个“东西”。这并不是一个对继承有意义的抽象。

于 2012-05-20T01:23:10.977 回答