Vererbung der Python-Klasse AttributeError - warum? wie repariert man?
Ähnliche Fragen zu SO sind:dieses unddiese. Ich habe auch die gesamte Online-Dokumentation durchgelesen, bin aber immer noch ziemlich verwirrt. Ich wäre Ihnen für Ihre Hilfe dankbar.
Ich möchte das Attribut Wand class .wandtype in meiner Lumus-Methode der CastSpell-Klasse verwenden. Aber ich bekomme immer wieder die Fehlermeldung "AttributeError: Das Objekt 'CastSpell' hat kein Attribut 'wandtype'."
Dieser Code funktioniert:
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()
Dieser Code wird bei einem Vererbungsversuch nicht verwendet.
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()
Ich habe erfolglos versucht, die super () -Methode zu verwenden. Ich würde mich sehr über Ihre Hilfe freuen, wenn Sie verstehen, a) warum die Klassenvererbung in diesem Fall nicht funktioniert, b) wie Sie sie zum Laufen bringen.