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 开发者_StackOverflow中文版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.
You could just initialize it with a default value:
self.father = None
That way the attribute will at least be recognized. And this is valid since at this point there really is no father
.
In response to your statement on Justin's answer, try this:
print ' Name %s Father %s '%(str(self.name), str(self.father.name))
The str() command will get a string representation of an object even if it's None
精彩评论