class constructors: class vs. instance defaults

Steve Holden steve at holdenweb.com
Thu Oct 7 01:09:12 CEST 2004


Erik Johnson <ej <at> wellkeeper wrote:

>     I am rather new to Python and still learning the finer points. I wanted
> to have a class which has a member dictionary of other class instances, a
> constructor that would initiate that dict with an empty dict if you didn't
> provide one, and a member function to stick more other classes into that
> dictionary.
> 
> I wrote something akin to this:
> 
> #! /usr/bin/python
> 
> #=======================================================================
> class Bar:
> 
>     def __init__(self, foo_d={}):
>         self.foo_d = foo_d
> 
>     def add_foo(self, foo):
>         self.foo_d[foo.key] = foo
> #=======================================================================
> 
[...]
> 
> 
>     A single, shared dictionary is definitely not what I wanted or expected
> and didn't see why it was happening.  So... I struggled with that for a
> while and eventually reasoned that the {} in the argument list to my
> constructor is executed at the time of class definition, and is essentially
> a reference to an instantiated dictionary object and therefor there is a
> little empty dictionary sitting in memory somewhere prior to me ever
> instantiating a Bar object. New Bar objects constructed without providing
> their own foo_d end up sharing that one.  I think this makes sense enough,
> now  (if I'm missing something, speak up).
> 
>     So, one work-around is to do this:
> 
> #=======================================================================
> class Bar:
> 
>     def __init__(self, foo_d=None)
>         if foo_d:
>             self.foo_d = foo_d
>         else:
>             self.foo_d = {}
> #=======================================================================
> 

[...]
> 
>     So... Yes? Is there a better way to do this sort of thing, or is that
> perfectly reasonable code?
> 
>     Thanks for taking the time to read my post! :)
> 
> -ej
> 
> 
Well you have managed to come up with the standard paradigm (and 
successfully diagnose one of the most common beginner's conundrums along 
the way) by the exercise of pure thought. I don't think there's much to 
add, except possibly "congratulations"!

regards
  Steve
-- 
http://www.holdenweb.com
http://pydish.holdenweb.com
Holden Web LLC +1 800 494 3119



More information about the Python-list mailing list