如何在同一目录或子目录中导入类?

问题:如何在同一目录或子目录中导入类?

我有一个存储所有.py文件的目录。

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

我想从使用类user.pydir.pymain.py
如何将这些Python类导入main.py
此外,User如果user.py位于子目录中,如何导入类?

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

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

回答 0

Python 2

在与文件__init__.py相同的目录中创建一个名为的空文件。这将向Python表示“可以从此目录导入”。

然后做…

from user import User
from dir import Dir

如果文件位于子目录中,则同样适用-也将一个__init__.py放在子目录中,然后使用带点标记的常规import语句。对于每个级别的目录,您都需要添加到导入路径。

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

因此,如果目录被命名为“ classes”,则可以这样做:

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

Python 3

与上一个相同,但是.如果不使用子目录,则在模块名称前添加一个:

from .user import User
from .dir import Dir

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

回答 1

我刚刚了解到(感谢martineau的评论),为了从同一目录中的文件导入类,您现在应该使用Python 3编写代码:

from .user import User
from .dir import Dir

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

回答 2

在您的main.py

from user import Class

Class您要导入的类的名称在哪里。

如果要调用的方法Class,则可以使用以下方法调用它:

Class.method

请注意,__init__.py同一目录中应该有一个空文件。

In your main.py:

from user import Class

where Class is the name of the class you want to import.

If you want to call a method of Class, you can call it using:

Class.method

Note that there should be an empty __init__.py file in the same directory.


回答 3

如果不想将函数和类与模块混合使用,则可以导入模块并通过其名称进行访问

import util # imports util.py

util.clean()
util.setup(4)

或者您可以将函数和类导入代码中

from util import clean, setup
clean()
setup(4)

您可以使用wildchar *将模块中的所有内容导入代码

from util import *
clean()
setup(4)

You can import the module and have access through its name if you don’t want to mix functions and classes with yours

import util # imports util.py

util.clean()
util.setup(4)

or you can import the functions and classes to your code

from util import clean, setup
clean()
setup(4)

you can use wildchar * to import everything in that module to your code

from util import *
clean()
setup(4)

回答 4

在python3,__init__.py不再需要。如果控制台的当前目录是python脚本所在的目录,则一切正常

import user

但是,如果从不包含的其他目录中调用,则此方法将无效user.py
在这种情况下,请使用

from . import user

即使您要导入整个文件,而不是仅从那里导入一个类,也可以使用该方法。

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.


回答 5

为了更容易理解:

第1步:转到一个目录,其中将包含所有目录

$ cd /var/tmp

步骤2:现在让我们制作一个class1.py文件,其文件名为Class1,并带有一些代码

$ cat > class1.py <<\EOF
class Class1:
    OKBLUE = '\033[94m'
    ENDC = '\033[0m'
    OK = OKBLUE + "[Class1 OK]: " + ENDC
EOF

步骤3:现在让我们制作一个class2.py文件,其文件名为Class2并带有一些代码

$ cat > class2.py <<\EOF
class Class2:
    OKBLUE = '\033[94m'
    ENDC = '\033[0m'
    OK = OKBLUE + "[Class2 OK]: " + ENDC
EOF

步骤4:现在让一个main.py可以执行一次以使用来自2个不同文件的Class1和Class2

$ cat > main.py <<\EOF
"""this is how we are actually calling class1.py and  from that file loading Class1"""
from class1 import Class1 
"""this is how we are actually calling class2.py and  from that file loading Class2"""
from class2 import Class2

print Class1.OK
print Class2.OK
EOF

步骤5:运行程序

$ python main.py

输出将是

[Class1 OK]: 
[Class2 OK]:

To make it more simple to understand:

Step 1: lets go to one directory, where all will be included

$ cd /var/tmp

Step 2: now lets make a class1.py file which has a class name Class1 with some code

$ cat > class1.py <<\EOF
class Class1:
    OKBLUE = '\033[94m'
    ENDC = '\033[0m'
    OK = OKBLUE + "[Class1 OK]: " + ENDC
EOF

Step 3: now lets make a class2.py file which has a class name Class2 with some code

$ cat > class2.py <<\EOF
class Class2:
    OKBLUE = '\033[94m'
    ENDC = '\033[0m'
    OK = OKBLUE + "[Class2 OK]: " + ENDC
EOF

Step 4: now lets make one main.py which will be execute once to use Class1 and Class2 from 2 different files

$ cat > main.py <<\EOF
"""this is how we are actually calling class1.py and  from that file loading Class1"""
from class1 import Class1 
"""this is how we are actually calling class2.py and  from that file loading Class2"""
from class2 import Class2

print Class1.OK
print Class2.OK
EOF

Step 5: Run the program

$ python main.py

The output would be

[Class1 OK]: 
[Class2 OK]:

回答 6

Python 3


一样directory

导入文件:log.py

导入类:SampleApp()

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

要么

目录是basic

导入文件:log.py

导入类:SampleApp()

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

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()

回答 7

from user import User 
from dir import Dir 
from user import User 
from dir import Dir 

回答 8

如果user.py和dir.py不包含类,则

from .user import User
from .dir import Dir

不管用。然后,您应该导入为

from . import user
from . import dir

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

回答 9

我不确定为什么可以使用Pycharm build from file_in_same_dir import class_name

IDE对此有所抱怨,但似乎仍然可以使用。我正在使用Python 3.7

I’m not sure why this work but using Pycharm build from file_in_same_dir import class_name

The IDE complained about it but it seems it still worked. I’m using Python 3.7


回答 10

太简单了,创建一个文件__init__.py为classes目录,然后将其导入到脚本中,如下所示(全部导入)

from classes.myscript import *

仅导入选定的类

from classes.myscript import User
from classes.myscript import Dir

Just too brief, Create a file __init__.py is classes directory and then import it to your script like following (Import all case)

from classes.myscript import *

Import selected classes only

from classes.myscript import User
from classes.myscript import Dir

回答 11

从同一目录导入

from . import the_file_you_want_to_import 

从子目录导入目录应该包含

初始化 .py

档案以外的档案,然后

从目录导入your_file

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


回答 12

Python3

采用

from .user import User inside dir.py file

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

像这样

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