无法在Python中访问父成员变量

Yar*_*rin 25 python inheritance scope

我正在尝试从扩展类访问父成员变量.但是运行以下代码......

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()
Run Code Online (Sandbox Code Playgroud)

得到我这个错误:

AttributeError: type object 'Mother' has no attribute '_haircolor'
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Ign*_*ams 31

你正在混淆类和实例属性.

print self._haircolor
Run Code Online (Sandbox Code Playgroud)


mVC*_*Chr 21

您需要实例属性,而不是类属性,因此您应该使用self._haircolor.

此外,你真的应该使用super,__init__以防你决定改变你的继承Father.

class Child(Mother):
    def __init__(self): 
        super(Child, self).__init__()
    def print_haircolor(self):
        print self._haircolor
Run Code Online (Sandbox Code Playgroud)