'Calling a method from another method inside the same class using getattr

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'



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1