用动态成员定义一个枚举的更多的pythonic方法 [英] A more pythonic way to define an enum with dynamic members

查看:136
本文介绍了用动态成员定义一个枚举的更多的pythonic方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个枚举来表示ISO国家代码。国家代码数据来自一个json文件,可以从以下文件获取: https ://github.com/lukes/ISO-3166-Countries-with-Regional-Codes

I needed to create an enum to represent the ISO country codes. The country code data comes from a json file which can be obtained from: https://github.com/lukes/ISO-3166-Countries-with-Regional-Codes

所以我所做的是:

data = json.load(open('slim-2.json'))
codes_list = [(data[i]['alpha-2'], int(data[i]['country-code']))
              for i in range(len(data))]

CountryCode = enum.Enum('CountryCode', codes_list,)

names_dict = {int(data[i]['country-code']):data[i]['name'] 
              for i in range(len(data))}
setattr(CountryCode, '_names', names_dict)

CountryCode.choices = classmethod(lambda cls:((member.value, name) 
                                  for name, member in cls.__members__.items()))
setattr(CountryCode, '__str__' ,lambda self: self.__class__._names[self.value])

这段代码片段坦白地丑陋。我查看了定义枚举类的另一种方法,但无法将解决方案拼凑起来。有没有办法以下列形式定义枚举:

This code snippet is frankly ugly. I looked at alternative ways to define the enum class but couldn't piece together a solution. Is there a way to define the enum in the following form:

class CountryCode(enum.Enum):

    data = json.load(open('slim-2.json'))
    # Some code to define the enum members

    @classmethod
    def choices(cls):
    # etc...

有关如何执行此操作的建议? p>

Any suggestions on how to do this?

推荐答案

这个怎么样?

data = json.load(open('slim-2.json'))
CountryCode = enum.Enum('CountryCode', [
    (x['alpha-2'], int(x['country-code'])) for x in data
])
CountryCode._names = {x['alpha-2']: x['name'] for x in data}
CountryCode.__str__ = lambda self: self._names[self.name]
CountryCode.choices = lambda: ((e.value, e.name) for e in CountryCode)




  • 已替换 [... data [i] ... for i in range (len(data))] with [... x ... for x in data] ;您可以在代码中使用itearte序列(list, data ),而不使用索引。

  • 使用 CountryCode.attr = ... 而不是混合 CountryCode.attr = ... setattr(CountryCode,'attr',...)

    • Replaced [...data[i]... for i in range(len(data))] with [...x... for x in data]; You can itearte sequence (list, data in the code) without using indexes.
    • Used CountryCode.attr = ... consistently; instead of mixing CountryCode.attr = ... and setattr(CountryCode, 'attr', ...).
    • 这篇关于用动态成员定义一个枚举的更多的pythonic方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆