类似的问题包括:this one和this。我也阅读了所有我能找到的在线文档,但我还是很困惑。我很感激你的帮助。
我想在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)如何让它起作用。
是的,
super()
不是你想要的。请参阅this article了解有关为什么不这样做的详细信息。Python中对超类的正常调用(不幸的是)是通过引用超类显式地完成的。
如果我正确地解释了您的问题,您会想为什么
.length
和.wandtype
属性没有出现在CastSpell
实例中。这是因为没有调用Wand.init)方法。你应该这样做:也就是说,你似乎没有使用继承权。施法是一个“动作”,而魔杖是一个“东西”。这并不是真正意义上的抽象继承。
您需要调用超类的init方法。否则,在当前的CastSpell实例上永远不会设置wandtype和length。
或者,可以将wandtype和length作为属性添加到init方法之外的对象上:
然后,它们将始终可用(尽管在初始化之前它们的值为None)。
但是,你确定施法应该是魔杖的一个子类吗?施法是一种动作,听起来更像是魔杖的一种方法。
简单地说,在继承它的类中重写
Wand.__init__
,因此CastSpell.wandtype
从不在CastSpell
中设置。除此之外,my_wand
无法将信息传递到cast_spell
,因此您对继承的作用感到困惑。不管你怎么做,你都必须把
length
和wandtype
传递给CastSpell
。一种方法是将它们直接包含到CastSpell.__init__
:另一种更通用的方法是将这两个传递给基类'own
__init__()
:另一种方法是停止使
CastSpell
从Wand
继承(是CastSpell
一种Wand
吗?或者是什么事情相反,让每根魔杖都有一些CastSpell
s在里面:不要使用“is-a”(aCastSpell
是一种Wand
),试试“has-a”(aWand
hasSpell
)。这里有一个简单的,不是很好的方法来拥有魔杖商店咒语:
相关问题 更多 >
编程相关推荐