one-time initialization of class members

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


On Jun 13, 8:00 pm, Larry Bates <larry.ba... at websafe.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.
>
> I could be missing something but dataset is shared among all the class
> instances.  If you reset it based on param it will be reset every time
> you create a new instance of the Base class with a different param.  Is
> that really what you want to do?  If so just use:
>
> class Base(object):
>     dataset = None
>
>     def __init__(self, param):
>         if self.dataset is None:
>             # code to load dataset based on param, expensive
>
> -Larry

I'm sorry, I somehow omitted the fact that the dataset does indeed
need to vary based on the child class, actually this is the main
difference between child classes.




More information about the Python-list mailing list