def'd类型的类常量

Sea*_*red 1 python singleton class

在Python中,有没有声明要声明的类型的类成员?

class Foo:
    def __init__(self, a, b):
        self.one = a
        self.two = b

    ZERO = Foo(0, 0)
    ONE = Foo(0, 1)
Run Code Online (Sandbox Code Playgroud)

这个问题似乎是由以下事实出现的类Foo没有完全在评估的时间def'd Foo.ZEROFoo.ONE-有什么办法来克服这一点的同时保持的形式Foo.MEMBER

Jam*_*arp 5

这似乎有效:

class Enum(object):
    def __init__(self, a, b): 
        self.one = a
        self.two = b 

    def __metaclass__(name, bases, dict):
        cls = type(name, bases, dict)
        cls.ZERO = cls(0, 0)
        cls.ONE = cls(0, 1)
        return cls 
Run Code Online (Sandbox Code Playgroud)