Basic Class/Instance Question

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Wed May 23 07:28:27 EDT 2007


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:

class A(object):
     def __init__(self, val=None):
         if val is None:
           val = []
         self.val=val

FWIW, do you really believe such a 'bug' would have stayed unnoticed ?-)

Else, the rest of the universe seems to be in place, and I don't know if 
she'll still like you if she learn you didn't read the FAQ before 
posting !-)

HTH



More information about the Python-list mailing list