I have a class in which I have properties that are returning arrays. For simplicity, let’s consider them constant:
JavaScript
x
16
16
1
import numpy as np
2
3
class MyClass:
4
def __init__(self):
5
self._time = np.array([0, 1, 2, 3])
6
self._a = np.array([0, 1, 2, 3])
7
self._b = np.array([4, 5, 6, 7])
8
9
@property
10
def a(self):
11
return self._a
12
13
@property
14
def b(self):
15
return self._b
16
Now, I have another class which is inheriting MyClass
and it is interpolating the data, for example:
JavaScript
1
13
13
1
class Interpolator(MyClass):
2
def __init__(self, vector):
3
super().__init__()
4
self._vector = np.array(vector)
5
6
@property
7
def a(self):
8
return np.interp(self._vector, self._time, self._a)
9
10
@property
11
def b(self):
12
return np.interp(self._vector, self._time, self._b)
13
Now, the issue is that I have 2 classes like MyClass
and each one of them consists of ~30 properties.
Is there a way to override all properties without doing it one by one? I was having a look also at this solution but I am not sure if/how I can apply it to my problem.
Advertisement
Answer
Refactor your superclass to “proxy”/”trampoline” those properties via a function you can override in a subclass:
JavaScript
1
29
29
1
import numpy as np
2
3
4
class MyClass:
5
def __init__(self):
6
self._time = np.array([0, 1, 2, 3])
7
self._a = np.array([0, 1, 2, 3])
8
self._b = np.array([4, 5, 6, 7])
9
10
def _get_property(self, v):
11
return v
12
13
@property
14
def a(self):
15
return self._get_property(self._a)
16
17
@property
18
def b(self):
19
return self._get_property(self._b)
20
21
22
class Interpolator(MyClass):
23
def __init__(self, vector):
24
super().__init__()
25
self._vector = np.array(vector)
26
27
def _get_property(self, v):
28
return np.interp(self._vector, self._time, v)
29