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

当前回答

# 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!

其他回答

# 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!
from user import User 
from dir import Dir 

如果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

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