Python is wierd!
Alex Martelli
alex at magenta.com
Thu Jul 27 03:26:59 EDT 2000
"David Bolen" <db3l at fitlinxx.com> wrote in message
news:u7la8m8ir.fsf at ctwd0143.fitlinxx.com...
[snip]
> If I'm going to package up some state (various bits of information)
> into a class (aka using one as a structure - data only), one approach
[snip]
> class MyInfo:
> def __init__(self):
> self.variable = initial_value
> self.other_variable = initial_value
[snip]
> I'm curious what others would think of the two approaches?
My instinct (and, again, since my Python experience is limited, it is
quite possible that my instinct is off-base!) would be to enrich the
second approach. If I'm "just packaging data", client code will
often want to give non-default initial values to one or more fields,
so, why not make it convenient.
If I have a good grasp on what fields will be actually used, then...:
class MyInfo:
def __init__(self, variable=None, other_variable=None):
self.variable = variable
self.other_variable = other_variable
If I don't really know what fields client-code will want to pack into
the structure, then...:
class MyInfo:
def __init__(self, **fields):
self.__dict__.update(fields)
In either case, a __getdict__ can also be a valuable adjunct
to turn name-errors into automagically-initialized fields (or, it
can be a "pitiful crutch", a lazy prop to avoid designing it right
in the first place -- depending on how keen one is towards
up-front design versus a more exploratory style:-).
Alex
More information about the Python-list
mailing list