Home > Back-end >  Calling a method from another method inside the same class using getattr
Calling a method from another method inside the same class using getattr

Time:05-17

I am not sure what is going wrong here.

import pandas as pd

class Data:
def __init__(self,database_name):
    self.database_name=database_name
    self.the_data_reader= getattr(Data, 'read_' database_name.lower())
def read_data(self):
    self.the_data_reader()
    # Parametros basicos da base
def read_opnosis(self):
    self.texts_df=pd.DataFrame(columns=['name','text']) 
    self.summaries_df=pd.DataFrame(columns=['name','summary'])
if __name__ == '__main__':
    data=Data('opnosis')
    data.read_data()

However, I am receiving this error:

TypeError: read_opnosis() missing 1 required positional argument: 'self'

CodePudding user response:

I think you need to use eval function.

import pandas as pd

class Data:
    def __init__(self,database_name):
        self.database_name=database_name
        self.the_data_reader= getattr(self, 'read_' database_name.lower())
    def read_data(self):
        self.the_data_reader()
        # Parametros basicos da base
    def read_opnosis(self):
        self.texts_df=pd.DataFrame(columns=['name','text']) 
        self.summaries_df=pd.DataFrame(columns=['name','summary'])
if __name__ == '__main__':
    data=Data('opnosis')
    data.read_data()

Hope it could help.

  • Related