我有一个枚举
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中实现它?
我的方法是这样的(也许不完美,但你明白了):
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)
希望这可以帮助。