0

so I have a data cleaning project that looks something like this:

import math
import os
import pandas as pd
import math


class CustomDataFrame():
    code    
class CustomDataFrameItem():
    code
class Util():
    code

class Program():
    code

if __name__ == "__main__":
    p = Program()
    p.run()

However, I wish to put the 4 classes into individual py files and have a main file with only

if __name__ == "__main__":
        p = Program()
        p.run()  

But I am not sure how to call all the class files if I separate them.

Can you show me what to do? Thank you in advance.

zhangruibo101
  • 67
  • 1
  • 10
  • Does this answer your question? [Importing class from another file](https://stackoverflow.com/questions/41276067/importing-class-from-another-file) – ThePyGuy Aug 26 '21 at 18:22

2 Answers2

1

I highly recommend checking out the official documentation or a tutorial to learn about the import command.

You can split them into individual files and import them if they are all in the same directory without any problems.

This answer assumes your directory has the following structure:

.
| - file1.py
| - file2.py
| - ...etc
| - main.py

If you wish to nest your directories, see the other answer. Their answer covers how to use __init__.py to take care of that.

If you have the classes defined in individual files, you only need to import standard libraries that are required for that script. For example, if CustomDataFrame required RequiredModule1 and RequiredModule2 but not matplotlib, you would write this in file1.py.

file1.py

import RequiredModule1
import RequiredModule2
#etc
class CustomDataFrame():
    code 

You can either separate them out into individual files, or group modules together into a single file and import each of them. file2.py

class CustomDataFrameItem():
    code 
class Program():
    code

main.py

from file1 import CustomDataFrame
from file2 import CustomDataFrameItem, Program
if __name__ == "__main__":
    p = Program()
    p.run()

Note that you do not put the file extension .py on the from fileX import xxx. The .py is inferred by the interpreter.

blackbrandt
  • 2,010
  • 1
  • 15
  • 32
1

In the case of file structure:

-main.py
-folder_1
 |---file1.py
 |---file2.py

It can be done by specifying the empty __init__.py file in the folder containing all the .py files.

which would look like this:

-main.py
-folder_1
 |---file1.py
 |---file2.py
 |---__init__.py
Roxy
  • 1,015
  • 7
  • 20