34

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?

Yarin
  • 173,523
  • 149
  • 402
  • 512

2 Answers2

39

You're mixing up class and instance attributes.

print self._haircolor
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
24

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
mVChr
  • 49,587
  • 11
  • 107
  • 104