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?

2 Answers 2

39

You're mixing up class and instance attributes.

print self._haircolor
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

What is super()'s behavior when confronted with multiple inheritance? Does the usual MRO kick in?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.