Importing classes from different files in a subdirectory

前端 未结 5 1310
深忆病人
深忆病人 2020-11-29 07:21

Here\'s the structure I\'m working with:

directory/
          script.py
          subdir/
                 __init__.py
                 myclass01.py
                 


        
5条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 08:03

    I use this simple way:

    1. add the directory to the system path, then
    2. import module or from module import function1, class1 in that directory.

    notice that the module is nothing but the name of your *.py file, without the extension part.

    Here is a general example:

    import sys
    sys.path.append("/path/to/folder/")
    import module # in that folder
    

    In your case it could be something like this:

    import sys
    sys.path.append("subdir/")
    import myclass01
    # or
    from myclass01 import func1, class1, class2 # .. etc
    

提交回复
热议问题