在python中的枚举转换器

use*_*618 6 python enums

我有一个枚举

class Nationality:
        Poland='PL'
        Germany='DE'
        France='FR'
        ...
        Spain='ES'
Run Code Online (Sandbox Code Playgroud)

我有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'
Run Code Online (Sandbox Code Playgroud)

这就是我想要调用这个方法的方法:

convert_country_code_to_country_name('DE') # I want here to  print 'Germany'
Run Code Online (Sandbox Code Playgroud)

如何在python中实现它?

nik*_*kow 5

最好的解决方案是从一开始就创建一个字典.你的枚举在Python中没有意义,它只是不必要的复杂.看起来你正在尝试编写Java代码,这与Python代码看起来完全相反.

  • @user:你只能创建一次字典,然后在其他模块中导入它 - 如果它是一个类,它就没有区别.通常,像Python这样的动态语言工作可能与Java或C#非常不同.它需要一些时间来适应它,但最终它是值得的努力,并使你成为一个整体更好的程序员. (4认同)

Bal*_*arq 1

我的方法是这样的(也许不完美,但你明白了):

class Nationality:
        Poland = 'PL'
        Germany = 'DE'
        France = 'FR'

        def convertToCodeFromName(name):
                return getattr(Nationality, name)

        def convertToNameFromCode(code):
                lookFor = None

                for member in dir(Nationality):
                        if (getattr(Nationality, member) == code):
                                lookFor = member
                                break
                return lookFor

print(Nationality.convertToCodeFromName("Poland"))
print(Nationality.convertToNameFromCode("PL"))
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。