classmethods, class variables and subclassing

Ron Adam rrr at ronadam.com
Fri Oct 21 14:02:35 EDT 2005


Andrew Jaffe wrote:

> Hi,
> 
> I have a class with various class-level variables which are used to 
> store global state information for all instances of a class. These are 
> set by a classmethod as in the following (in reality the setcvar method 
> is more complicated than this!):
> 
> class sup(object):
>     cvar1 = None
>     cvar2 = None
> 
>     @classmethod
>     def setcvar1(cls, val):
>         cls.cvar1 = val
> 
>     @classmethod
>     def setcvar2(cls, val):
>         cls.cvar2 = val
> 
>     @classmethod
>     def printcvars(cls):
>     print cls.cvar1, cls.cvar2

How about just using a mutable list?

class sup(object):
    states = [None,None]       # [s1, s2, ...]
    def set_s1(self, val):
        self.states[0] = val
    def get_s1(self):
        return self.states[0]
    def set_s2(self, val):
        self.states[1] = val
    def get_s2(self):
        return self.states[1]

It keeps the states because the list isn't ever reassigned after it's 
created, so the values in it can change and all instances and subclasses 
can see the changed values.

Cheers,
    Ron





More information about the Python-list mailing list