How to pass variable to base class

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.

# -*- coding: utf-8 -*-
"""
Created on Thu Jun 23 14:13:14 2022

@author: ilja
"""

from matplotlib import pyplot as plt
import math
import numpy as np


class Signal:
    def __init__(self, length):
        self.length = length
        self.data = None
        
        
    def write_data(self,data):
        self.data = data
    
        
    def plot(self):
        plt.figure(1)
        x = [i for i in range(self.length)]
        plt.plot(x, self.data)
        plt.show()
    
    
    def integrate(self):
        # TODO
        pass


class Harmonic(Signal):
    def __init__(self, periods, amplitude, frequency):
        super().__init__(int(2*math.pi*periods))
        self.amplitude = amplitude
        self.frequency = frequency
        super().write_data(self.sample())
    
    
    def sample(self):
        return [self.amplitude * math.sin(i*self.frequency) for i in range(self.length)]
    

if __name__ == '__main__':
    sig = Harmonic(7,3,1/2)
    sig.plot()

>Solution :

Well, since Harmonics is "based" on Signal, you can acces the attributes defined in Signal. You can simply write:

class Harmonic(Signal):
    def __init__(self, periods, amplitude, frequency):
        super().__init__(int(2*math.pi*periods))
        self.amplitude = amplitude
        self.frequency = frequency
        self.data = self.sample()

So, instead of

super().write_data(self.sample())

you write only

self.data = self.sample()

Leave a Reply