循环遍历类似枚举的所有变量

时间:2013-11-01 18:14:53

标签: python python-2.7 enums python-2.x

我有一个类似于枚举的类。 我想循环他的变量(枚举的值)

class Demos(object):
    class DemoType(object):
        def __init__(self, name):
            self.name = name

        def __repr__(self):
            return self.name

    VARIABLE1 = DemoType("Car")
    VARIABLE2 = DemoType("Bus")
    VARIABLE3 = DemoType("Example")
    VARIABLE4 = DemoType("Example2")

我考虑使用Role.__dict__vars(Role),但它们不仅包含变量,还包含RoleType类和其他属性,如__module____doc__以及更多......

我也希望它像这样表示,主要是因为它会向DemoType添加更多变量。 name以外的变量,所以请尝试以这种方式找到答案。

2 个答案:

答案 0 :(得分:1)

不是重新发明枚举类型,而是使用Python的Enum类型(也是backported)更好。然后你的代码看起来像

class Demos(Enum):
    VARIABLE1 = "Car"
    VARIABLE2 = "Bus"
    VARIABLE3 = "Example"
    VARIABLE4 = "Example2"


--> for variable in Demos:
...    print variable

答案 1 :(得分:0)

我找到了答案,而且它根本不是How can I represent an 'Enum' in Python?的副本。 答案是通过以下list创建以下list comprehensive

variables = [attr for attr in dir(Demos()) if not attr.startswith("__") and not callable(attr)]
print variables 

我还可以创建一个函数来为我这样做:

class Demos(object):
    class DemoType(object):
        def __init__(self, name):
            self.name = name

        def __repr__(self):
            return self.name

    @classmethod
    def get_variables(cls):
        return [getattr(cls, attr) for attr in dir(cls) if not callable(getattr(cls, attr)) and not attr.startswith("__")]

    VARIABLE1 = DemoType("Car")
    VARIABLE2 = DemoType("Bus")
    VARIABLE3 = DemoType("Example")
    VARIABLE4 = DemoType("Example2")


for variable in Demos.get_variables():
    print variable