2012-04-08 1 views
20

में मूल सदस्य चर का उपयोग नहीं कर सकता है मैं एक विस्तारित वर्ग से अभिभावक सदस्य चर का उपयोग करने का प्रयास कर रहा हूं।पायथन

AttributeError: type object 'Mother' has no attribute '_haircolor' 

क्या मैं गलत कर रहा हूँ: लेकिन निम्नलिखित कोड चल रहा है ...

class Mother(object): 
    def __init__(self): 
     self._haircolor = "Brown" 

class Child(Mother): 
    def __init__(self): 
     Mother.__init__(self) 
    def print_haircolor(self): 
     print Mother._haircolor 

c = Child() 
c.print_haircolor() 

मुझे इस त्रुटि हो जाता है?

उत्तर

27

आप कक्षा और उदाहरण विशेषताओं को मिश्रित कर रहे हैं।

print self._haircolor 
+10

एक बेवकूफ – Yarin

19

आप क्लास विशेषता नहीं, उदाहरण विशेषता चाहते हैं, तो आपको self._haircolor का उपयोग करना चाहिए।

इसके अलावा, आप वास्तव में super__init__ में आप Father या कुछ और करने के लिए अपने विरासत को बदलने का फैसला मामले में प्रयोग करना चाहिए।

class Child(Mother): 
    def __init__(self): 
     super(Child, self).__init__() 
    def print_haircolor(self): 
     print self._haircolor 
+0

im धन्यवाद mVChr- तुम सही हो मैं धन्यवाद – Yarin

+1

जब एकाधिक वंशानुक्रम के साथ सामना किया 'सुपर()' के व्यवहार क्या है should-? क्या सामान्य एमआरओ लात मारता है? –

+1

http://stackoverflow.com/questions/3277367/how-does-pythons-super-work-with- बहु- विरासत – mVChr