Python类继承属性错误-为什么?如何修复?

2024-06-02 05:22:03 发布

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

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

我想在CastSpell类lumus方法中使用Wand class.wandtype属性。但我一直得到错误“attribute error:”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)如何让它起作用。


Tags: theselfinitdefwandlengthclassprint
3条回答

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

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

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

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

也就是说,你似乎没有使用继承权。施法是一个“动作”,而魔杖是一个“东西”。这并不是真正意义上的抽象继承。

您需要调用超类的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

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

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

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


但是,你确定施法应该是魔杖的一个子类吗?施法是一种动作,听起来更像是魔杖的一种方法。

class Wand(object):
    [...]
    def cast_spell(self, spell, thing):
         [etc.]

简单地说,在继承它的类中重写Wand.__init__,因此CastSpell.wandtype从不在CastSpell中设置。除此之外,my_wand无法将信息传递到cast_spell,因此您对继承的作用感到困惑。

不管你怎么做,你都必须把lengthwandtype传递给CastSpell。一种方法是将它们直接包含到CastSpell.__init__

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

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

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

另一种方法是停止使CastSpellWand继承(是CastSpell一种Wand吗?或者是什么事情相反,让每根魔杖都有一些CastSpells在里面:不要使用“is-a”(aCastSpell是一种Wand),试试“has-a”(aWandhasSpell)。

这里有一个简单的,不是很好的方法来拥有魔杖商店咒语:

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"

相关问题 更多 >