Home > Software engineering >  How to pass variable to base class
How to pass variable to base class

Time:06-24

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()

CodePudding user response:

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()

CodePudding user response:

I would say, you should override the function plot() in Harmonic class. Because the concept is: You keep the common abstract idea in the base class, and go into specific implementation in the inherited class. So yes, each signal has a plot() function. How to plot() a specific signal such as Harmonic() is a subject for Harmonic class not for the base class. Base class(Signal) only ensure that inherited class(Harmonic) has a basic implementation of plot().

`class Singal():
     def __init__():
         .
         return
     plot():
         .
         return
 class Harmonic(Signal):
     def __init__():
         .
         return
     def plot():
         .
         return`
  • Related