class constructors: class vs. instance defaults

Michael Hoffman m.h.3.9.1.without.dots.at.cam.ac.uk at example.com
Thu Oct 7 01:07:31 CEST 2004


Dan Perl wrote:

> I think that a more "pythonic" way to implement your class is with a change 
> in the definition of your __init__:
>     def __init__(self, foo_d=dict({})):
> This will create a separate copy for each one of your class instances 
> instead of the common object that you are creating in the definition of the 
> function.

Actually it does exactly what the original code did <wink>.

 >>> def x(d=dict({})): return d
...
 >>> a = x()
 >>> b = x()
 >>> a
{}
 >>> b
{}
 >>> a[3] = 4
 >>> b
{3: 4}

Taking out the {} doesn't help either.
-- 
Michael Hoffman



More information about the Python-list mailing list