简单地说,在继承它的类中重写Wand.__init__,因此CastSpell.wandtype从不在CastSpell中设置。除此之外,my_wand无法将信息传递到cast_spell,因此您对继承的作用感到困惑。
不管你怎么做,你都必须把length和wandtype传递给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)
另一种方法是停止使CastSpell从Wand继承(是CastSpell一种Wand吗?或者是什么事情相反,让每根魔杖都有一些CastSpells在里面:不要使用“is-a”(aCastSpell是一种Wand),试试“has-a”(aWandhasSpell)。
这里有一个简单的,不是很好的方法来拥有魔杖商店咒语:class Wand(object):
def