我有一个存放所有.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

当前回答

如果user.py和dir.py不包括类,那么

from .user import User
from .dir import Dir

不起作用。然后您应该导入as

from . import user
from . import dir

其他回答

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

from .user import User
from .dir import Dir

从同一目录导入

from . import the_file_you_want_to_import 

要从目录应包含的子目录导入

init.py

那就别写你的文件了

从目录导入your_file

我不能为顶部的答案提交编辑,所以根据上面评论中给出的一些指针,另一件要尝试的事情是:

from subfolder.MyClassFile import MyClass

就是这样。只要记住在我们的子文件夹中有一个__init__.py空文件。

仅供参考,如果你的结构是这样的,解决方案是有效的:

your_project/
    __ini__.py
    main.py
    subfolder/
        __init__.py
        MyClassFile.py  <-- You want this

MyClassFile.py包含MyClass类。

实际上,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 ...
# My Python version: 3.7
# IDE: Pycharm 2021.1.2 Community

# Have "myLib" in folder "labs":

class Points:
    def __init__(self, x = 0, y = 0):
        self.__x = x
        self.__y = y
    def __str__(self):
        return f"x = {self.__x}, y = {self.__y}"

# Have "myFile" in (same) folder "labs":

from myFile import Point

p1 = Point(1, 4)
p2 = Point(1, 4)
print(f"p1: {p1}, p2: {p2}")

# Result:
# p1: x = 1, y = 4, p2: x = 1, y = 4

# Good Luck!