class constructors: class vs. instance defaults
Dan Perl
danperl at rogers.com
Wed Oct 6 18:52:16 EDT 2004
"Erik Johnson wellkeeper com>" <ej <atdot> wrote in message
news:416472df at nntp.zianet.com...
>
> 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
> #=======================================================================
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.
Dan
More information about the Python-list
mailing list