mercredi 7 février 2018

Python design pattern for magic methods and pandas inheritance

So I basically put this question for some advice

I have few classes which basically does some pandas operations and return a dataframe. But these dataframes needs addition and subtraction on some filter options. I planned to write a class to override __add__ and __sub__ methods, so that these dataframes are added or subtracted by my code which implements those filters. Below is a basic structure

import ArithOperation
class A:
  def dataA(self):
    return ArithOperation(dfA)

class B:
  def dataB(self):
    return ArithOperation(dfB)

dfA and dfB here are pandas dataframes.

class ArithOperation:
  def __init__(self, df):
     self.df = df
  def __add__(self, other):
     # here the filtering and manual addition is done
     return ArithOperation(sumdf)
  def __sub__(self, other):
     # here the filtering and manual subtraction is done
     return ArithOperation(deltadf)

Basically I do the calculation as below

dfa = A().dataA()
dfb = B().dataB()

sumdf = dfa+dfb
deltadf = dfa-dfb

But how do I make the sumdf and deltadf have default dataframe functions too. I know I should inherit dataframe object to ArithOperation but I am confused and bit uncomfortable of instantiating ArithOperation() at many places.

  1. Is there a better design pattern for this problem?
  2. Which class to inherit on ArithOperation so that I have all pandas dataframe functions too on ArithOperation object ?

Aucun commentaire:

Enregistrer un commentaire