'Once' properties.

Scott David Daniels Scott.Daniels at Acm.Org
Tue Oct 6 02:50:12 EDT 2009


menomnon wrote:
> Does python have a ‘once’ (per class) feature?
> 
> ‘Once’, as I’ve know it is in Eiffel.  May be in Java don’t.
> 
> The first time you instantiate a given class into an object it
> constructs, say, a dictionary containing static information.  In my
> case static is information that may change once a week at the most and
> there’s no need to be refreshing this data during a single running of
> the program (currently maybe 30 minutes).
> 
> So you instantiate the same class into a second object, but instead of
> going to the databases again and recreating the same dictionary a
> second time, you get a pointer or reference to the one already created
> in the first object – copies into the second object that is.  And the
> dictionary, no matter how many instances of the object you make, is
> always the same one from the first object.
> 
> So, as we put it, once per class and not object.
> 
> Saves on both time and space.
Look into metaclasses:

     class MyType(type):
         def __new__(class_, name, bases, dct):
             result = type.__new__(class_, name, bases, dct)
             result._init_class()
             return result

     class ClassBase(object):
         __metaclass__ = MyType

         @classmethod
         def _init_class(class_):
             print 'initializing class'


     class Initialized(ClassBase):
         @classmethod
         def _init_class(class_):
             class_.a, class_.b = 1, 2
             super(Initialized, class_)._init_class()

     print Initialized.a, Initialized.b

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list