栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

什么时候应该继承EnumMeta而不是Enum?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

什么时候应该继承EnumMeta而不是Enum?

首先,查看不进行子类化时所需的代码

Enummeta

stdlib方式

from enum import Enumimport jsonclass baseCountry(Enum):    def __new__(cls, record):        member = object.__new__(cls)        member.country_name = record['name']        member.pre = int(record['country-pre'])        member.abbr = record['alpha-2']        member._value_ = member.abbr, member.pre, member.country_name        if not hasattr(cls, '_choices'): cls._choices = {}        cls._choices[member.pre] = member.country_name        cls._choices[member.abbr] = member.country_name        return member         def __str__(self):        return self.country_nameCountry = baseCountry(        'Country',        [(rec['alpha-2'], rec) for rec in json.load(open('slim-2.json'))],        )

aenum
方法 1 2

from aenum import Enum, MultiValueimport jsonclass Country(Enum, init='abbr pre country_name', settings=MultiValue):    _ignore_ = 'country this'  # do not add these names as members    # create members    this = vars()    for country in json.load(open('slim-2.json')):        this[country['alpha-2']] = (     country['alpha-2'],     int(country['country-pre']),     country['name'],     )    # have str() print just the country name    def __str__(self):        return self.country_name

上面的代码适合一次性枚举-但是如果从JSON文件创建枚举对您来说很普遍怎么办?想象一下您是否可以这样做:

class Country(JSONEnum):    _init_ = 'abbr pre country_name'  # remove if not using aenum    _file = 'some_file.json'    _name = 'alpha-2'    _value = { 1: ('alpha-2', None), 2: ('country-pre', lambda c: int(c)), 3: ('name', None), }

如你看到的:

  • _file
    是要使用的json文件的名称
  • _name
    是该名称应使用的路径
  • _value
    是将路径映射到值3的字典
  • _init_
    指定不同值组件的属性名称(如果使用
    aenum

JSON数据摘自https://github.com/lukes/ISO-3166-Countries-with-Regional-Codes-
以下
是简短摘录:

[{“ name”:“ Afghanistan”,“ alpha-2”:“ AF”,“国家/地区代码”:“ 004”},

{“ name”:“ÅlandIslands”,“ alpha-2”:“ AX”,“国家/地区代码”:“ 248”},

{“名称”:“阿尔巴尼亚”,“ alpha-2”:“ AL”,“国家代码”:“ 008”},

{“名称”:“阿尔及利亚”,“ alpha-2”:“ DZ”,“国家/地区代码”:“ 012”}]

这是

JSONEnummeta
课程:

class JSonEnummeta(Enummeta):    @classmethod    def __prepare__(metacls, cls, bases, **kwds):        # return a standard dictionary for the initial processing        return {}    def __init__(cls, *args , **kwds):        super(JSONEnummeta, cls).__init__(*args)    def __new__(metacls, cls, bases, clsdict, **kwds):        import json        members = []        missing = [    name    for name in ('_file', '_name', '_value')    if name not in clsdict    ]        if len(missing) in (1, 2): # all three must be present or absent raise TypeError('missing required settings: %r' % (missing, ))        if not missing: # process name_spec = clsdict.pop('_name') if not isinstance(name_spec, (tuple, list)):     name_spec = (name_spec, ) value_spec = clsdict.pop('_value') file = clsdict.pop('_file') with open(file) as f:     json_data = json.load(f) for data in json_data:     values = []     name = data[name_spec[0]]     for piece in name_spec[1:]:         name = name[piece]     for order, (value_path, func) in sorted(value_spec.items()):         if not isinstance(value_path, (list, tuple)):  value_path = (value_path, )         value = data[value_path[0]]         for piece in value_path[1:]:  value = value[piece]         if func is not None:  value = func(value)         values.append(value)     values = tuple(values)     members.append(         (name, values)         )        # get the real EnumDict        enum_dict = super(JSONEnummeta, metacls).__prepare__(cls, bases, **kwds)        # transfer the original dict content, _items first        items = list(clsdict.items())        items.sort(key=lambda p: (0 if p[0][0] == '_' else 1, p))        for name, value in items: enum_dict[name] = value        # add the members        for name, value in members: enum_dict[name] = value        return super(JSONEnummeta, metacls).__new__(metacls, cls, bases, enum_dict, **kwds)# for use with both Python 2/3JSonEnum = JSonEnummeta('JsonEnum', (Enum, ), {})

一些注意事项:

  • JSONEnummeta.__prepare__
    返回正常
    dict

  • Enummeta.__prepare__
    用于获取的实例
    _EnumDict
    -这是获取实例的正确方法

  • 带下划线的键将被传递给实数

    _EnumDict
    优先,因为在处理枚举成员时可能需要它们

  • 枚举成员的顺序与文件中的顺序相同


1披露:我是Python
stdlib

Enum
enum34
backport和Advanced
Enumeration(
aenum
) 库的作者。

2这需要

aenum 2.0.5+

3键是数字键,可以在需要多个值时按顺序保留多个值

Enum



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/637598.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号