staticmethod behaviour
Samu
samufuentes at gmail.com
Wed Aug 25 09:58:46 EDT 2010
On Aug 25, 3:26 pm, Peter Otten <__pete... at web.de> wrote:
> 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
Ahh, thank you very much for the link. Now I understand. I remember
having read that before, but it is not until you face the problem that
the concept sticks. But why does it have a different behaviour the
staticmethod with the "rights3" case then?
More information about the Python-list
mailing list