# Posted By

manatlan on 10/07/09

# Statistics

Viewed 396 times
Favorited by 0 user(s)

# Create class definitions of properties (typed and ordered) with metaclass

/ Published in: Python
`import os class _FieldBase_:    _defines=[]    def __init__(self,*a):        _FieldBase_._defines.append(self) class _FieldedMetaClass_(type):    def __init__(cls, name, bases, dct):        super(_FieldedMetaClass_, cls).__init__(name, bases, dct)        if name!="Form":            fields_to_name = dict([(slot,name) for name,slot in dct.items() if isinstance(slot,_FieldBase_)])            cls.fields = [(fields_to_name[obj],obj ) for obj in _FieldBase_._defines]            _FieldBase_._defines=[] # reset list !!! class Form (object):    __metaclass__ = _FieldedMetaClass_     def __repr__(self):        l=["Form '%s'"%self.__class__.__name__]        l+=["* %-10s : %s"%(f,t.__class__.__name__) for f,t in self.fields]        return os.linesep.join(l) class FieldInt(_FieldBase_):    def __init__(self,*a):        _FieldBase_.__init__(self,a) class FieldString(_FieldBase_):    def __init__(self,*a):        _FieldBase_.__init__(self,a) class Form1(Form):    name     = FieldString(1)    surname  = FieldString(2)    age      = FieldInt(3) class Form2(Form):    nb      = FieldInt(1)    title   = FieldString(2) print Form1()print Form2()`