Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't access parent member variable in Python

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?

like image 925
Yarin Avatar asked Apr 08 '12 17:04

Yarin


People also ask

How do you access the members of a parent class in Python?

Accessing Parent Class Functions This is really simple, you just have to call the constructor of parent class inside the constructor of child class and then the object of a child class can access the methods and attributes of the parent class.

How do you inherit a variable from a parent class in Python?

Add the __init__() Function So far we have created a child class that inherits the properties and methods from its parent. We want to add the __init__() function to the child class (instead of the pass keyword).

How do you view parent objects in Python?

return self # expose object to be able call age_diff() etc. class Parent(SimpleNamespace): child_name = ChildName(name='Bar') child_diff = ChildDiff(born=42) parent = Parent(name='Foo', born=23) print(parent.

Can a child class access parent variables?

The reference holding the child class object reference will not be able to access the members (functions or variables) of the child class. This is because the parent reference variable can only access fields that are in the parent class.


1 Answers

You're mixing up class and instance attributes.

print self._haircolor 
like image 139
Ignacio Vazquez-Abrams Avatar answered Oct 08 '22 10:10

Ignacio Vazquez-Abrams