एसओ पर इसी तरह के प्रश्नों में शामिल हैं: this one और this। मैंने उन सभी ऑनलाइन दस्तावेजों के माध्यम से भी पढ़ा है जिन्हें मैं पा सकता हूं, लेकिन मैं अभी भी काफी उलझन में हूं। मैं आपकी मदद के लिए आभारी रहूंगा।पायथन कक्षा विरासत विशेषताएँ त्रुटि - क्यों? कैसे ठीक करना है?
मैं अपने कास्टस्पेल क्लास लुमस विधि में वंड क्लास। 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()
मैंने सुपर() विधि का उपयोग करने का कोई फायदा नहीं लिया है। मैं वास्तव में आपकी मदद की सराहना करता हूं ए) इस मामले में कक्षा विरासत क्यों काम नहीं कर रही है, बी) इसे कैसे काम पर लाया जाए।
क्या 'CastSpell' ऑब्जेक्ट वास्तव में * एक 'वंड' ऑब्जेक्ट होना चाहिए? – Darthfett
मैं बस .wandtype विशेषता प्राप्त करना चाहता था, यही कारण है कि मैंने इसका उपयोग किया है। यह थोड़ा अजीब लगता है, मुझे पता है। – user1186742
क्यों 'वर्तनी' विधि के साथ 'वर्तनी' श्रेणी नहीं है, जो कि केवल वंड प्रकार को तर्क के रूप में लेता है? – Darthfett