Python:将常量的值转换为常量的名称

时间:2014-01-19 00:53:59

标签: python reflection

如果我有这样的课程:

class MyClass:
    ONE = 1
    TWO = 2

有没有办法使用反射或其他一些Python功能简化下面的代码?

def class_value_to_string(my_class_num):
    if my_class_num == MyClass.ONE:
        return "ONE"
    elif my_class_num == MyClass.TWO:
        return "TWO"
    else:
        return "UNKNOWN VALUE"

2 个答案:

答案 0 :(得分:3)

您可以枚举类的属性并反转查找:

enum_names = {value: name for name, value in vars(MyClass).items() if name.isupper()}

使用此功能,您可以将值映射回名称。

演示:

>>> class MyClass:
...     ONE = 1
...     TWO = 2
... 
>>> enum_names = {value: name for name, value in vars(MyClass).items() if name.isupper()}
>>> enum_names[1]
'ONE'

答案 1 :(得分:1)

class MyClass:
    ONE = 1
    TWO = 2
    def func(self):
        return 105

def foo():
    return 204

MyClass.akfoo = foo

def class_value_to_string(my_class_num,the_class):
    try:
        return (k for k,v in the_class.__dict__.iteritems() if v==my_class_num).next()
    except:
        return "UNKNOWN VALUE"

print class_value_to_string(1,MyClass)
print class_value_to_string(2,MyClass)
print class_value_to_string(3,MyClass)
print class_value_to_string(MyClass.func.im_func,MyClass)
print class_value_to_string(foo,MyClass)

结果

ONE
TWO
UNKNOWN VALUE
func
akfoo