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?
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.
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).
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.
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.
You're mixing up class and instance attributes.
print self._haircolor
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With