Skip to content Skip to sidebar Skip to footer

Create Static Instances Of A Class Inside Said Class In Python

Apologies if I've got the terminology wrong here—I can't think what this particular idiom would be called. I've been trying to create a Python 3 class that statically declares in

Solution 1:

After you defined the class, just add these two lines:

Test.A = Test("A")
Test.B = Test("B")

A class in Python is an object like any other and you can add new variables at any time. You just can't do it inside the class since it's not defined at that time (it will be added to the symbol table only after the whole code for the class has been parsed correctly).

Solution 2:

While the Aaron's answer is the preferred way you can also use metaclasses:

>>>classTestMeta(type):...def__init__(cls, name, bases, dct):...  cls.A = cls()...  cls.B = cls()...>>>classTest:...  __metaclass__ = TestMeta...>>>Test
<class __main__.Test at 0x7f70f8799770>
>>>Test.A
<__main__.Test object at 0x7f70f86f2e10>
>>>Test.B
<__main__.Test object at 0x7f70f86f2e90>
>>>

Solution 3:

In Python, a class block isn't just a declaration; it's executed at run time to build the class. Each def inside the class builds a function and binds the name into the class's namespace. For that reason, you can't simply do A = MyClass() directly inside the class block, because MyClass() isn't fully defined until the class block closes. Here's how to do it:

classTest:def__init__(self, value):
        self.value = value

    def__str__(self):
       return"Test: " + self.value

Test.A = Test("A")
Test.B = Test("B")

Post a Comment for "Create Static Instances Of A Class Inside Said Class In Python"