python 中的枚举转换器
我有一个枚举
class Nationality:
Poland='PL'
Germany='DE'
France='FR'
...
Spain='ES'
我有2个方法原型:
# I want somethink like in c#
def convert_country_code_to_country_name(country_code):
print Enum.Parse(typeof(Nationality),country_code)
#this a second solution ,but it has a lot of ifs
def convert_country_code_to_country_name(country_code):
if country_code=='DE':
print Nationality.Germany #btw how to print here 'Germany', instead 'DE'
这就是我想要调用这个方法的方式:
convert_country_code_to_country_name('DE') # I want here to print 'Germany'
如何在python中实现它?
I have an enum
class Nationality:
Poland='PL'
Germany='DE'
France='FR'
...
Spain='ES'
I have 2 prototypes of methods:
# I want somethink like in c#
def convert_country_code_to_country_name(country_code):
print Enum.Parse(typeof(Nationality),country_code)
#this a second solution ,but it has a lot of ifs
def convert_country_code_to_country_name(country_code):
if country_code=='DE':
print Nationality.Germany #btw how to print here 'Germany', instead 'DE'
This is how I want call this method:
convert_country_code_to_country_name('DE') # I want here to print 'Germany'
How to implement it in python?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
最好的解决方案是从一开始就创建一本字典。你的枚举在Python中没有意义,它只是不必要地复杂。看起来您正在尝试编写 Java 代码,这是与 Python 代码的预期完全相反。
The best solution would be to create a dictionary right from the start. Your enum doesn't make sense in Python, its just unnecessarily complex. It looks like you are trying to write Java code, which is quite the opposite of what Python code is supposed to look like.
Python 3.4 有一个新的 Enum 数据类型(已向后移植),它可以轻松支持您的用例:
从名称获取枚举成员:
从值获取枚举成员:
一旦获得枚举成员:
Python 3.4 has a new Enum data type (which has been backported), which easily supports your use case:
To get the enum member from the name:
To get the enum member from the value:
And once you have the enum member:
现在:
nationalityDict['DE']
包含Germany
。And now:
nationalityDict['DE']
containsGermany
.你想用 dict 代替吗?
Would you like to use dict instead?
我的方法就像这样(也许不完美,但你明白了):
希望这会有所帮助。
My approach would be like this one (maybe not perfect, but you get the idea):
Hope this helps.
转换为枚举的纯方法怎么样?只需将其存储在 util lib 中即可。或者您可以将其放在基 Enum 类上,并将 target_enum 默认为 self。
还可以调整它以引发异常,而不是使用默认值,但默认值更适合我的特定情况。
这是它的单元测试类。
How about a pure method for converting to enum? Just stash this in a util lib. Or you could put it on a base Enum class and have target_enum default to self.
Could also tweak this to raise an exception instead of using the default value, but the default worked better for my specific case.
Here is the unittest class for it.