SO上的類似問題包括:this one和this。我也閱讀了所有我能找到的在線文檔,但我仍然很困惑。我會很感激你的幫助。Python類繼承AttributeError - 爲什麼?怎麼修?
我想在我的CastSpell類lumus方法中使用魔杖類.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'對象? – Darthfett
我只是想獲得.wandtype屬性,這就是我使用它的原因。我知道這聽起來有點奇怪。 – user1186742
爲什麼不用'cast'方法創建一個'Spell'類,它只需要將魔杖類型作爲參數? – Darthfett