我想在python中创建一个类,其中包括该类的特殊实例的类级常量。例如:
class Testing:
SPECIAL = Testing("special")
def __init__(self, name):
self.name = name
def test_specials():
norm = Testing("norm")
assert norm.name == "norm"
assert Testing.SPECIAL.name == "special"
如果我尝试上面的代码,它会失败地说:NameError: name 'Testing' is not defined
。
我应该如何建模?
感谢Anthony的回答。解决方案是:
class Testing:
def __init__(self, name):
self.name = name
Testing.SPECIAL = Testing("special")
def test_specials():
norm = Testing("norm")
assert norm.name == "norm"
assert Testing.SPECIAL.name == "special"