Can';t在Python中访问父成员变量
我正在尝试从扩展类访问父成员变量。但是运行下面的代码Can';t在Python中访问父成员变量,python,inheritance,scope,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
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'
我做错了什么?您混淆了类和实例属性
print self._haircolor
您需要的是实例属性,而不是类属性,因此应该使用
self.\u haircolor
此外,如果您决定将继承更改为父继承或其他内容,您确实应该在\uuuu init\uuuu
中使用super
class Child(Mother):
def __init__(self):
super(Child, self).__init__()
def print_haircolor(self):
print self._haircolor
当遇到多重继承时,super()
的行为是什么?通常的MRO开始工作了吗?