How to import the class within the same directory

2020-01-22 12:32发布

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

I want to use classes from user.py and dir.py in main.py.
How can I import these Python classes into main.py?
Furthermore, how can I import class User if user.py is in a sub directory?

bin/
    dir.py
    main.py
    usr/
        user.py

12条回答
We Are One
2楼-- · 2020-01-22 12:34

Python 3


Same directory.

import file:log.py

import class: SampleApp().

import log
if __name__ == "__main__":
    app = log.SampleApp()
    app.mainloop()

or

directory is basic.

import in file: log.py.

import class: SampleApp().

from basic import log
if __name__ == "__main__":
    app = log.SampleApp()
    app.mainloop()
查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-01-22 12:34

If user.py and dir.py are not including classes then

from .user import User
from .dir import Dir

is not working. You should then import as

from . import user
from . import dir
查看更多
闹够了就滚
4楼-- · 2020-01-22 12:35

Python 2

Make an empty file called __init__.py in the same directory as the files. That will signify to Python that it's "ok to import from this directory".

Then just do...

from user import User
from dir import Dir

The same holds true if the files are in a subdirectory - put an __init__.py in the subdirectory as well, and then use regular import statements, with dot notation. For each level of directory, you need to add to the import path.

bin/
    main.py
    classes/
        user.py
        dir.py

So if the directory was named "classes", then you'd do this:

from classes.user import User
from classes.dir import Dir

Python 3

Same as previous, but prefix the module name with a . if not using a subdirectory:

from .user import User
from .dir import Dir
查看更多
欢心
5楼-- · 2020-01-22 12:40

to import from the same directory

from . import the_file_you_want_to_import 

to import from sub directory the directory should contain

init.py

file other than you files then

from directory import your_file

查看更多
放我归山
6楼-- · 2020-01-22 12:42

I just learned (thanks to martineau's comment) that, in order to import classes from files within the same directory, you would now write in Python 3:

from .user import User
from .dir import Dir
查看更多
叛逆
7楼-- · 2020-01-22 12:44

Python3

use

from .user import User inside dir.py file

and

use from class.dir import Dir inside main.py
or from class.usr import User inside main.py

like so

查看更多
登录 后发表回答