0

I want to create a class in python that includes class level constants for special instances of the class. i.e. something like this:

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"

If I try the above code, it fails saying: NameError: name 'Testing' is not defined.

How should I model this?

Dave Potts
  • 1,543
  • 2
  • 22
  • 33
  • 2
    the `Testing` name isn't available until after the class body is complete -- you'll need to do `Testing.SPECIAL = Testing("special")` after the class body – anthony sottile Jan 10 '21 at 22:24
  • Does this answer your question? [Create new class instance from class method](https://stackoverflow.com/questions/13260557/create-new-class-instance-from-class-method) – Coder Jan 10 '21 at 22:31
  • @JohnD, this is a different question: how to set up a class level instance variable rather than how to return a new instance from a class method. – Dave Potts Jan 12 '21 at 21:16

1 Answers1

2

Thanks to Anthony for the answer above. The solution is this:

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"
Dave Potts
  • 1,543
  • 2
  • 22
  • 33