0

I am writing my first classes in separate .py scripts, that I would like then import and call in the final main.py file/function.

However, for me it is a bit unclear how to use main function inside a class and then how to call that class in separate file after import is done.

Example of what I have tried so far:

dataload.py:

class Preprocess:

    def __init__(self):

        self.data = None
        self.data_ops = None


    def load_data(self):

        data_dir = os.path.join('...')
        imo_data = os.path.join("...")

        self.data = pd.read_csv(os.path.join(imo_data,"file1.csv"), low_memory=False)
        self.data_ops = pd.read_csv(os.path.join(data_dir,"file2.csv"),sep=";")    


    def run(self):

        self.load_data()

       

def main():

    p=Preprocess()
    p.run()

 

if __name__ == "__main__":

    main()

to be loaded and run in:

main.py:

import dataload
def main():
    dataload.Preprocess()
if __name__ == "__main__":

    main()

My expectation was that in this way I can just import this class in the new call and call it as dataload.Preprocess() in main() function and it would run in. However, it seems it does not work as I am not obtaining any objects (loaded dataframes) as I do when I just run p=Preprocess() p.run() without using main functions.

Anyone willing to explain and correct me, please? i have read several threads however it seems still a bit unclear to me. I am new to OBP. THanks@@

C.Nivs
  • 12,353
  • 2
  • 19
  • 44
Filip
  • 45
  • 2
  • The `main()` function in the module isn't called when you import it. That's the whole point of the `if __name__ == "__main__":` statement. You need to call `.run()` in `main.py` – Barmar Aug 28 '23 at 15:33
  • Or you could call `dataload.main()` from `main.py`. – Barmar Aug 28 '23 at 15:37

0 Answers0