Bug or feature?

Johann Hibschman johann at physics.berkeley.edu
Fri May 14 14:03:50 EDT 1999


Michael Hudson writes:

> That's C++ for heaven's sake! I know C++ far too well, you don't need
> to explain to me what static variables are in C++. This is Python, I
> know what they are here too, but they aren't (IMHO) as useful.

Well, I tend to use them more as class constants, rather than class
variables.

For example, I have a class which provides a "pickling interface" for
a C structure.  The structure contains many slots, only a few of which
are conceptually mutable.  So I wrote a mirror class which will pickle
only the mutable slots, then reconstruct the C structure when
requested.

While doing this, the class needed lists of the attributes contained
in the structure and which of those attributes were mutable.  Since
these lists of attributes should not change between instances, I made
them class-level variables.

class ConstsMirror:
    "Mirrors a C consts object, but allows pickling."
    # attributes of Const objects
    all_attrs = ['m', 'c', 'alpha', 'lambdaC', 'Bq', 'Bstar', 'rhoStar',
                 'rStar', 'thetac', 'nb', 'lnlambda']
    # this gives the mutable constant objects (not m, c, alpha, lambdaC)
    mutable_attrs = ['Bstar', 'rhoStar', 'rStar', 'thetac', 'lnlambda']

    def __init__ (self, consts_instance=None):
        # look up the "mutable_attrs" in the consts instance and
        # record them as local vars
        if not consts_instance:
            consts_instance = Cascade.Consts()
        for attr in self.mutable_attrs:
            setattr (self, attr, getattr (consts_instance, attr))

    def make_consts (self):
        c = Cascade.Consts()
        for attr in self.mutable_attrs:
            setattr (c, attr, getattr (self, attr))
        return c

    # etc.

Well, that's at least once example where I foun them useful.

--Johann

-- 
Johann Hibschman                           johann at physics.berkeley.edu




More information about the Python-list mailing list