Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is instance variable behaving like a class variable in Python? [duplicate]

Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument

I have the following code:

class Node(object):
    def __init__(self, value = 0, children = {}):
        self.val = value
        self.children = children

    def setChildValue(self, index, childValue):
        self.children[index] = Node(childValue)

n = Node()
n.setChildValue(0,10)
print n.children
n2 = Node()
print n2.children

And it prints:

{0: <__main__.Node object at 0x10586de90>}
{0: <__main__.Node object at 0x10586de90>}

So my question is, why is children defined in n2? Children is an instance variable and yet it's acting like a class variable.

Thanks

like image 359
Alex Varga Avatar asked Nov 21 '25 01:11

Alex Varga


2 Answers

You're assigning the same dictionary to children on every instance.

like image 75
kindall Avatar answered Nov 23 '25 21:11

kindall


When you define the function __init__ you give it a dictionary as a default argument. That dictionary is created once (when you define the function) and then used every time __init__ is called.

More information: http://effbot.org/zone/default-values.htm

like image 37
Matt Avatar answered Nov 23 '25 21:11

Matt