如何在python中为特殊类实例建模

  • 本文关键字:实例 建模 python python
  • 更新时间 :
  • 英文 :


我想在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"

最新更新