Skip to main content
 首页 » 编程设计

python之被定义类型的类常量

2025年05月04日17www_RR

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

class Foo: 
    def __init__(self, a, b): 
        self.one = a 
        self.two = b 
 
    ZERO = Foo(0, 0) 
    ONE = Foo(0, 1) 

这个问题似乎是因为类 Foo 在评估 Foo.ZERO 和 Foo 时没有完全定义.ONE - 有没有办法在保持 Foo.MEMBER 形式的同时克服这个问题?

请您参考如下方法:

这似乎可行:

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