Similar questions on SO include: this one and this. I’ve also read through all the online documentation I can find, but I’m still quite confused. I’d be grateful for your help.
I want to use the Wand class .wandtype attribute in my CastSpell class lumus method. But I keep getting the error “AttributeError: ‘CastSpell’ object has no attribute ‘wandtype’.”
This code works:
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()
This code, with attempted inheritance, doesn’t.
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()
I’ve tried using the super() method to no avail. I’d really appreciate your help understanding a) why class inheritance isn’t working in this case, b) how to get it to work.
To put it simply, you override
Wand.__init__in the class that inherits from it, soCastSpell.wandtypeis never set inCastSpell. Besides that,my_wandcan’t pass information intocast_spell, so you’re confused about the role of inheritance.Regardless of how you do it, you have to somehow pass
lengthandwandtypetoCastSpell. One way would be to include them directly intoCastSpell.__init__:Another, more generic way would be to pass these two to the base class’ own
__init__():Another way would be to stop making
CastSpellinherit fromWand(isCastSpella kind ofWand? or something aWanddoes?) and instead make each Wand be able to have someCastSpells in it: instead of “is-a” (aCastSpellis a kind ofWand), try “has-a” (aWandhasSpells).Here’s a simple, not so great way to have a Wand store spells: