使用元类创建属性(类型化和有序)的类定义
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用元类创建属性(类型化和有序)的类定义相关的知识,希望对你有一定的参考价值。
Like Django.models, GAE.db.model or SqlAlchemy definitions
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()
以上是关于使用元类创建属性(类型化和有序)的类定义的主要内容,如果未能解决你的问题,请参考以下文章