2012-04-08 10 views
20

拡張クラスから親メンバー変数にアクセスしようとしています。しかし、次のコードを実行している...Pythonの親メンバー変数にアクセスできない

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() 

は私に、このエラーを取得します:

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

は私が間違って何をしているのですか?

答えて

27

クラス属性とインスタンス属性が混在しています。

print self._haircolor 
+10

thanks-イム馬鹿 – Yarin

19

クラス属性ではなくインスタンス属性が必要なので、self._haircolorを使用する必要があります。

また、Fatherなどに継承を変更する場合は、__init__superを使用する必要があります。あなたは正しいmVChr-複数の継承に直面したとき

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

は、私は感謝 – Yarin

+1

何である 'スーパー()'の振る舞いをshould-?通常のMROはキックインしますか? –

+1

http://stackoverflow.com/questions/3277367/how-does-pythons-super-work-with-multiple-inheritance – mVChr

関連する問題