Can't access parent member variable in Python

让人想犯罪 __ 提交于 2020-07-04 07:25:22

问题


I'm trying to access a parent member variable from an extended class. But running the following code...

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

Gets me this error:

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

What am I doing wrong?


回答1:


You're mixing up class and instance attributes.

print self._haircolor



回答2:


You want the instance attribute, not the class attribute, so you should use self._haircolor.

Also, you really should use super in the __init__ in case you decide to change your inheritance to Father or something.

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


来源:https://stackoverflow.com/questions/10064688/cant-access-parent-member-variable-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!