tags:

views:

58

answers:

2

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.

+2  A: 

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.

Justin Ethier
I forgot to mention that I've already done that and I obtained:` print ' Name %s Father %s '%(self.name, self.father.name)AttributeError: 'NoneType' object has no attribute 'name'`
LB
crap, that's because that was not initialized when i reached this point of the program. right ?
LB
Correct, you need to make sure father isn't None before you can use name.
unholysampler
I think that's the stupidest question i've asked so far. :-)
LB
Asking stupid questions isn't stupid though; at least you're learning - we've all been there (at least) once ;-)
Jon Cage
A: 

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

Jon Cage
Why would that help? It's simply that at the time the print statement is run, self.father is still None...
mjv
It would stop the application crashing. I agree that it doesn't solve the underlying problem though.
Jon Cage