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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4142151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:25:45  来源:igfitidea点击:

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

pythonpython-import

提问by Bin Chen

I have a directory that stores all the .pyfiles.

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

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

I want to use classes from user.pyand dir.pyin main.py.
How can I import these Python classes into main.py?
Furthermore, how can I import class Userif user.pyis in a sub directory?

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

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

采纳答案by Amber

Python 2

蟒蛇 2

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

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

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__.pyin 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.

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

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

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

所以如果目录被命名为“classes”,那么你会这样做:

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

Python 3

蟒蛇 3

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

与之前相同,但在模块名称前加上.if 不使用子目录:

from .user import User
from .dir import Dir

回答by demas

from user import User 
from dir import Dir 

回答by user225312

In your main.py:

在您的main.py

from user import Class

where Classis the name of the class you want to import.

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

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

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

Class.method

Class.method

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

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

回答by user225312

To make it more simple to understand:

为了更容易理解:

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

第 1 步:让我们转到一个目录,所有目录都将包含在该目录中

$ cd /var/tmp

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

第 2 步:现在让我们创建一个 class1.py 文件,它的类名 Class1 和一些代码

$ cat > class1.py <<\EOF
class Class1:
    OKBLUE = '3[94m'
    ENDC = '3[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

第 3 步:现在让我们创建一个 class2.py 文件,它的类名 Class2 和一些代码

$ cat > class2.py <<\EOF
class Class2:
    OKBLUE = '3[94m'
    ENDC = '3[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

第 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

Step 5: Run the program

第五步:运行程序

$ python main.py

The output would be

输出将是

[Class1 OK]: 
[Class2 OK]:

回答by A.Zaben

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)

回答by ecp

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:

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

from .user import User
from .dir import Dir

回答by Shafiq

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

太简短了,创建一个文件__init__.py是 classes 目录,然后将其导入到您的脚本中,如下所示(导入所有案例)

from classes.myscript import *

Import selected classes only

仅导入选定的类

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

回答by Yasith Praharshana

Python 3

蟒蛇 3



Same directory.

一样directory

import file:log.py

导入文件:log.py

import class: SampleApp().

导入类:SampleApp().

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

or

或者

directory is basic.

目录是basic.

import in file: log.py.

导入文件:log.py.

import class: SampleApp().

导入类:SampleApp().

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

回答by lucidbrot

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

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

import user

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

但是,如果从不包含user.py.
在这种情况下,请使用

from . import user

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

即使您想从那里导入整个文件而不仅仅是一个类,这也有效。

回答by rojo_hlerr

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

初始化.py

file other than you files then

文件以外的文件然后

from directory import your_file

从目录导入 your_file