Suppose I have a class, defined, for example, thus:
JavaScript
x
7
1
class testclass():
2
cl = []
3
4
def __init__(self, x):
5
self.cl.append(x)
6
7
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:
JavaScript
1
31
31
1
class Meta(type):
2
def __init__(cls, *args):
3
cls.cl = []
4
5
class testclass(metaclass=Meta):
6
def __init__(self, n):
7
self.cl.append(n)
8
9
class t_child(testclass):
10
pass
11
12
t = testclass(10)
13
print(t.cl)
14
# [10]
15
16
t2 = testclass(20)
17
print(t2.cl)
18
# [10, 20]
19
20
t3 = t_child(100)
21
print(t3.cl)
22
# [100]
23
24
t4 = t_child(100)
25
print(t4.cl)
26
# [100, 100]
27
28
t5 = testclass(30)
29
print(t5.cl)
30
# [10, 20, 30]
31