注意这个问题不是关于Python 3 Enum
数据类型,它只是我正在使用的示例。为什么我应该使用__prepare__方法来获得类的名称空间?
PEP 3115随着Python 3的添加__prepare__
方法type
用于允许创建类时使用的自定义名称空间的目的。例如,新的Enum
数据类型使用__prepare__
返回专用_EnumDict
的实例,以用作新的Enum
类的名称空间。
然而,我看到的几个例子对SO的EnumMeta
被子类,创建用于在元类__new__
方法的类新的命名空间,但是,而不是调用__prepare__
方法,以获取新的命名空间,则使用type(clsdict)()
代替。这样做有风险吗?
为__prepare__
签名:
def __new__(metacls, cls, bases, clsdict, **kwds):
实施例使用type(clsdict)
:
@classmethod
def __prepare__(metacls, cls, bases, **kwds):
和__new__
class CountryCodeMeta(enum.EnumMeta):
def __new__(metacls, cls, bases, classdict):
data = classdict['data']
names = [(country['alpha-2'], int(country['country-code'])) for country in data]
--> temp = type(classdict)()
for name, value in names:
temp[name] = value
excluded = set(temp) | set(('data',))
temp.update(item for item in classdict.items() if item[0] not in excluded)
return super(CountryCodeMeta, metacls).__new__(metacls, cls, bases, temp)