Possible Duplicate:
Static class variables in Python
Python OOP and lists
just wondering if I could get some help on this.
I am using python, and have hit an obstacle that I can't seem to figure out with a small program I am working on. Here is my problem (using a very simple and unrelated example): I have a class:
class dog:
name = ''
friends = []
I make a couple objects from it:
fido = dog()
rex = dog()
And here is where I get stuck. I don't know why this is happening and I haven't figured it out. I'm assuming my understanding of something is deficient though, any explanation would be great. So here is my problem, if I append one object to the other (which seems like it should work just fine):
fido.friends.append(rex)
... things mess up. As you can see here:
>>> fido.friends.append(rex)
>>> fido.friends
[<__main__.dog instance at 0x0241BAA8>]
>>> rex.friends
[<__main__.dog instance at 0x0241BAA8>]
>>>
That just deosn't make sense to me. Shouldn't only fido.friends have something in it? Even if I make a new object:
rover = dog()
It has a dog instance in it, which we can see is our 'rex' object.
>>> rex.name = "rex"
>>> fido.friends[0].name
'rex'
>>> rex.friends[0].name
'rex'
>>> rover.friends[0].name
'rex'
>>>
This just isn't making sense, and I'd love some help. I searched around for awhile trying to find an explanation, but didn't. Sorry if there is a similar question I missed.