staticmethod behaviour

Peter Otten __peter__ at web.de
Wed Aug 25 09:26:10 EDT 2010


Samu wrote:

> Hi,
> 
> I run today into some problems with my code and I realized that there
> is something in the behaviours of the @staticmethod that I don't
> really understand. I don't know if it is an error or not, actually,
> only that it was, definitely, unexpected.
> 
> I wrote a small demo of what happens.

> The code:

> class User:
>  def __init__(self, id=None, rights=[], rights2=[], rights3=[]):
>   self.id = id
>   self.rights = rights
>   self.rights2 = rights2
>   self.rights3 = rights3
>  @staticmethod
>  def cr_user():
>   user = User(1, ['read'], rights3=[])
>   user.rights.append('write')
>   user.rights2.append('write2')
>   user.rights3.append('write3')
>   return user
> 
> print "User created with static: id, rights, rights2"
> a = User.cr_user()
> print a.id, a.rights, a.rights2, a.rights3
> print "User created with User()"
> b = User()
> print b.id, b.rights, b.rights2, a.rights3

> The answer I get:
> User created with static: id, rights, rights2
> 1 ['read', 'write'] ['write2'] ['write3']
> User created with User()
> None [] ['write2'] ['write3']
> 
> I was expecting either all arrays from the second to be [] or to be a
> copy of the first one.
> 
> If someone can provide an explanation, I would be thankful :)

The problem is not the staticmethod, it's the mutable default values for 
__init__(). See

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

Peter




More information about the Python-list mailing list