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

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

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

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

当前回答

Python 2

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

那就…

from user import User
from dir import Dir

如果文件在子目录中,同样适用-在子目录中也放入__init__.py,然后使用点表示法的常规导入语句。对于每一层目录,都需要添加到导入路径中。

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

其他回答

为了更容易理解:

步骤1:让我们进入一个目录,在那里所有将包括

$ cd /var/tmp

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

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

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

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

步骤4:现在让我们创建一个main.py,它将执行一次,使用来自两个不同文件的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

第五步:运行程序

$ python main.py

输出将是

[Class1 OK]: 
[Class2 OK]:

我刚刚了解到(感谢martineau的评论),为了从同一目录中的文件导入类,你现在可以在Python 3中写道:

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

实际上,Python并没有为这种日常用例提供优雅的解决方案。当您正在测试最终将作为Python包的一部分交付的代码时,这尤其成问题。下面是一个对我很有效的方法:

迪尔 |

file1.py file2.py

假设你想从file1导入file2。

# In file1.py:
try:
     # This works when packaged as Python package
     from . import file2
except:
     # This works when simply invoking file1 as a module (i.e. python file1)
     import file2

# rest of the code ...

对于python3

from .user import用户 从侄子导入:从。usr。user import用户