How to import the class within the same directory or sub directory?

后端 未结 13 927
醉梦人生
醉梦人生 2020-11-22 06:34

I have a directory that stores all the .py files.

bin/
   main.py
   user.py # where class User resides
   dir.py # where class Dir resides
         


        
13条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 06:54

    In python3, __init__.py is no longer necessary. If the current directory of the console is the directory where the python script is located, everything works fine with

    import user
    

    However, this won't work if called from a different directory, which does not contain user.py.
    In that case, use

    from . import user
    

    This works even if you want to import the whole file instead of just a class from there.

提交回复
热议问题