Consider the following Python code (Python 3):
- I have a class
Signal
comprising all the functions signals of all different kinds should be able to perform. - For each kind of signal, I create a new class, where the data is “sampled”, meaning an array with signal data is specified.
If I now want to plot the signal, the plot
method of the super()
class is called. However, in order to plot the data, the Signal
class must somehow access it. Now my question is: What is the cleanest way to pass the signal data to the Signal
class?
I have the feeling that there must be a better way than the super().write_data(self.sample())
approach.
JavaScript
x
51
51
1
# -*- coding: utf-8 -*-
2
"""
3
Created on Thu Jun 23 14:13:14 2022
4
5
@author: ilja
6
"""
7
8
from matplotlib import pyplot as plt
9
import math
10
import numpy as np
11
12
13
class Signal:
14
def __init__(self, length):
15
self.length = length
16
self.data = None
17
18
19
def write_data(self,data):
20
self.data = data
21
22
23
def plot(self):
24
plt.figure(1)
25
x = [i for i in range(self.length)]
26
plt.plot(x, self.data)
27
plt.show()
28
29
30
def integrate(self):
31
# TODO
32
pass
33
34
35
class Harmonic(Signal):
36
def __init__(self, periods, amplitude, frequency):
37
super().__init__(int(2*math.pi*periods))
38
self.amplitude = amplitude
39
self.frequency = frequency
40
super().write_data(self.sample())
41
42
43
def sample(self):
44
return [self.amplitude * math.sin(i*self.frequency) for i in range(self.length)]
45
46
47
if __name__ == '__main__':
48
sig = Harmonic(7,3,1/2)
49
sig.plot()
50
51
Advertisement
Answer
Well, since Harmonics is “based” on Signal, you can acces the attributes defined in Signal. You can simply write:
JavaScript
1
7
1
class Harmonic(Signal):
2
def __init__(self, periods, amplitude, frequency):
3
super().__init__(int(2*math.pi*periods))
4
self.amplitude = amplitude
5
self.frequency = frequency
6
self.data = self.sample()
7
So, instead of
JavaScript
1
2
1
super().write_data(self.sample())
2
you write only
JavaScript
1
2
1
self.data = self.sample()
2