Home > Software engineering >  How to let python class metod inherit library functions?
How to let python class metod inherit library functions?

Time:02-22

Part of a class I am writing is a wrapper for plotting with matplotlib.

however, I want my wrapper to still be able to pass all plotting options.

Example:

import matplotlib as plt
import numpy as np

class parentclass():
   def __init__(self):
       #functions to read some data
       data=np.arange(100)

   def plotaline(self,customargument1,customargument2,**kwargs):
       cmin=customargument1*2
       cmax=customargument2*4
       #these are just for the sake of having other arguments

       plt.plot(self.data,vmin=cmin,vmax=vmax,**kwargs)

# expected: 
mydata=parentclass()
#plots a data line with red crosses as it takes the args that usually would go into plt.plot()
mydata.plotaline(0,1,'r- ')



I know something is missing. I need a way to pass the "plot" method from the plt library to my class method. maybe it's some logic i am missing here, granted I probably do not know enough about inheritance.

Help would be much appreciated.

CodePudding user response:

Add *args and **kwargs to include both optional positional arguments and keyword arguments.

def plotaline(self,customargument1,customargument2, *args, **kwargs):
       cmin=customargument1*2
       cmax=customargument2*4
       #these are just for the sake of having other arguments

       plt.plot(self.data,vmin=cmin,vmax=vmax, *args, **kwargs)
  • Related