one-time initialization of class members

James Turk james.p.turk at gmail.com
Thu Jun 14 01:55:02 CEST 2007


On Jun 13, 6:54 pm, Steven Bethard <steven.beth... at gmail.com> wrote:
> James Turk wrote:
> > Hi,
>
> > I have a situation where I have some class members that should only be
> > done once.  Essentially my problem looks like this:
>
> > class Base(object):
> >     dataset = None
>
> >     def __init__(self, param):
> >         if type(self).dataset is None:
> >             # code to load dataset based on param, expensive
>
> > class ChildClass1(Base):
> >     def __init__(self):
> >         Base.__init__(self, data_params)
>
> > class AnotherChildClass(Base):
> >     def __init__(self):
> >         Base.__init__(self, other_data_params)
>
> > This seems to work, initialization is only done at the first creation
> > of either class.  I was just wondering if this is the 'pythonic' way
> > to do this as my solution does feel a bit hackish.
>
> What should happen with code like::
>
>      ChildClass1('foo')
>      ChildClass1('bar')
>
> The 'param' is different, but 'dataset' should only get set the first time?
>
> STeVe

ChildClass doesn't take the parameter in it's constructor, it supplies
it for the BaseClass.  Every ChildClass of the same type should use
the same dataset.




More information about the Python-list mailing list