如果你想记录这些定义的顺序,你需要传递一个 自定义词典来跟踪班级中的作业 代码(基本上是包含类套件的普通python函数)。 不幸的是,这个字典 - 你后来看到的元类__new __()方法的分类元素 参数 - 始终是用C创建的字典, ,如最近讨论的那样clpy(对不起,但我记得的所有关键词都是 ''metaclass''和''martelli'' - 不是很有选择性:-)。下面是我的(笨拙) 尝试解决方法: 导入itertools 类OrderedValue(对象) : newIndex = itertools.count(1).next def __init __(self,value): self.value = value self.index = self.newIndex() class Meta(类型): def __new __(mcl,name,bases, classdict): 断言ordered_names不在课堂上 values = [] for(n,v)in classdict.iteritems(): 尝试: v,i = v.value,v.index 除了AttributeError: pass else: values.append((i,n,v)) values.sort() ordered_names = [] for(i,n,v)的值: ordered_names.append(n) classdict [n] = v classdict [" ordered_names"] = ordered_names 返回类型.__ new __(mcl,name,bases,classdict) class Base: __metaclass__ = Meta 类演示(基础): alpha = 0 beta = OrderedValue(1 ) gamma = OrderedValue(17) delta = OrderedValue(3) 打印Demo.ordered_names 打印Demo.alpha,Demo.beta PeterIf you want to record the order of these definitions, you need to pass acustom dictionary that keeps track of assignments in the class generationcode (basically a normal python function comprising the class suite).Unfortunately that dictionary - which you see later as the classdictparameter of the metaclass __new__() method - is always a dict created in C,as was recently discussed on c.l.py (sorry, but all keywords I remember are''metaclass'' and ''martelli'' - not very selective :-). Below is my (clumsy)attempt for a workaround:import itertoolsclass OrderedValue(object):newIndex = itertools.count(1).nextdef __init__(self, value):self.value = valueself.index = self.newIndex()class Meta(type):def __new__(mcl, name, bases, classdict):assert "ordered_names" not in classdictvalues = []for (n, v) in classdict.iteritems():try:v, i = v.value, v.indexexcept AttributeError:passelse:values.append((i, n, v))values.sort()ordered_names = []for (i, n, v) in values:ordered_names.append(n)classdict[n] = vclassdict["ordered_names"] = ordered_namesreturn type.__new__(mcl, name, bases, classdict)class Base:__metaclass__ = Metaclass Demo(Base):alpha = 0beta = OrderedValue(1)gamma = OrderedValue(17)delta = OrderedValue(3)print Demo.ordered_namesprint Demo.alpha, Demo.betaPeter 这篇关于在元类中订购的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 1403页,肝出来的.. 09-08 04:30