Skip to content
Advertisement

a simple way to produces classes with global state

Suppose I have a class, defined, for example, thus:

class testclass():
    cl = []

    def __init__(self, x):
        self.cl.append(x)
    

Now, I want to create a class which is identical to testclass except I don’t want testclass’ state cl, but rather its own individual state.

Experiment shows that inheriting from testclass inherits cl, so that does not work. Any words of wisdom appreciated. Does this require the whole metaclass machinery? (which I don’t quite understand enough yet)

Advertisement

Answer

A metaclass isn’t so hard here if you just think of it as a subclass of the class type. You can give it an __init__() that sets the cl list just like you would for an instance and each class get’s its own class property:

class Meta(type):
    def __init__(cls, *args):
        cls.cl = []
    
class testclass(metaclass=Meta):        
    def __init__(self, n):
        self.cl.append(n)

class t_child(testclass):
    pass

t = testclass(10)
print(t.cl)
# [10]

t2 = testclass(20)
print(t2.cl)
# [10, 20]

t3 = t_child(100)
print(t3.cl)
# [100]

t4 = t_child(100)
print(t4.cl)
# [100, 100]

t5 = testclass(30)
print(t5.cl)
# [10, 20, 30]
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement