In Python, how to make data members visible to subclasses if not known when initializing an object ?
Posted
by LB
on Stack Overflow
See other posts from Stack Overflow
or by LB
Published on 2010-04-02T13:26:59Z
Indexed on
2010/04/02
13:33 UTC
Read the original article
Hit count: 176
python
The title is a bit long, but it should be pretty straightforward for someone well-aware of python.
I'm a python newbie. So, maybe i'm doing things in the wrong way.
Suppose I have a class TreeNode
class TreeNode(Node):
def __init__(self, name, id):
Node.__init__(self, name, id)
self.children = []
and a subclass with a weight:
class WeightedNode(TreeNode):
def __init__(self,name, id):
TreeNode.__init__(self, name, id)
self.weight = 0
So far, i think I'm ok. Now, I want to add an object variable called father in TreeNode so that WeightedNode has also this member. The problem is that I don't know when initializing the object who is going to be the father. I set the father afterwards with this method in TreeNode :
def set_father(self, father_node):
self.father = father_node
The problem is then when i'm trying to access self.father in Weighted:
print 'Name %s Father %s '%(self.name, self.father.name)
I obtain:
AttributeError: WeightedNode instance has no attribute 'father'
I thought that I could make father
visible by doing something in TreeNode.__init__
but i wasn't able to find what.
How can i do that ?
Thanks.
© Stack Overflow or respective owner