Using metaclasses to inherit class variables

telesphore4 at gmail.com telesphore4 at gmail.com
Mon May 22 12:33:01 EDT 2006


OK no question. I'm only posting b/c it may be something another newbie
will want to google in the future. Now that I've worked thru the
process this turns out to be fairly easy.

However, if there are better ways please let me know.

Module = ClassVars.py

import copy

class ClassVars(type):
    classVars = {}
    def __init__(cls, name, bases, dict):
        for name, value in type(cls).classVars.iteritems():
            if name not in dict:
                setattr(cls, name, copy.copy(value))

count = 0 # Not really needed but it semed nice to name the new types
def are(dict):
    global count
    count += 1
    return type('ClassVars%d' % count, (ClassVars,),
               {'classVars':dict})


To use in another module:

import ClassVars

class MyClass(str):
    __metaclass__ = ClassVars.are(dict(name=None, desc=None,
            myList=[]))

    # Rest of class definition ...


Thanks for the help.
t4




More information about the Python-list mailing list