【发布时间】:2012-05-27 01:18:30
【问题描述】:
关于 SO 的类似问题包括:this one 和 this。我还阅读了所有我能找到的在线文档,但我仍然很困惑。非常感谢您的帮助。
我想在我的 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)如何让它工作。
【问题讨论】:
-
“CastSpell”对象真的应该是“Wand”对象吗?
-
我只是想获得 .wandtype 属性,这就是我使用它的原因。这听起来有点奇怪,我知道。
-
为什么没有一个带有
cast方法的Spell类,它只是将魔杖类型作为参数? -
这很有意义。 :D 谢谢你的建议。不过,就继承而言,我确实很困惑,所以下面的答案很有帮助。
-
根据您的需要,您可以有一个
PhoenixFeatherWand类、一个Lumus类、一个WingardiumLeviosa类等。在典型的面向对象语言中,您可能有这些继承自Wand或Spell类,但由于 python 是一种鸭式语言,您可以让它们定义相同的接口,例如cast方法、size属性、name属性等.
标签: python class inheritance