On 2007-05-23, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: > Siah a écrit : >> Ready to go insane here. Class A, taking on a default value for a >> variable. Instantiating two separate objects of A() gives me a shared >> val list object. Just see the example bellow: >> >> >> class A(object): >> def __init__(self, val=[]): >> self.val=val >> >> obj1 = A() >> obj2 = A() >> >> print obj1 is obj2 # False - as expected >> print obj1.val is obj2.val # True! - Why... oh god WHY > > >> >> ----------- >> Using python 2.4. Is this a bug with this version of python? How can I >> trust the rest of the universe is still in place? Could she still like >> me? Many questions I have. Lets start with the python problem for now. > > This is a FAQ. Default arguments are only evaled once - when the def > statement is evaled (which is usually at import time). The solution is > simple: don't use mutable objects as default arguments:
An immutable object would have given the same behaviour in this case class A(object): def __init__(self, val = ()): self.val=val obj1 = A() obj2 = A() print obj1 is obj2 # False print obj1.val is obj2.val # True -- http://mail.python.org/mailman/listinfo/python-list