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) 機能させる方法を理解していただければ幸いです。