首页 > 解决方案 > 如何在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.

我应该如何建模?

标签: python

解决方案


感谢安东尼的上述回答。解决方案是这样的:

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"

推荐阅读