LB40
LB40

Reputation: 12331

In Python, how to make data members visible to subclasses if not known when initializing an object?

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.

Upvotes: 1

Views: 220

Answers (2)

Jon Cage
Jon Cage

Reputation: 37488

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

Upvotes: 0

Justin Ethier
Justin Ethier

Reputation: 134177

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.

Upvotes: 2

Related Questions