如何从 Python3 中的子目录导入函数

how to import function from sub directory in Python3

我有一个结构如下的项目:

TestDir.init.py 包含:

from . import TestSubDirFile

TestDir.TestSubDirFile.py 包含:

class TestSubDirFile:
def test_funct(self):
    print("Hello World")

ds_scheduler.py 包含:

from TestDir import TestSubDirFile as tp

def test_job():
    testobj = tp.test_funct()
    print("Test job executed.")

if __name__ == "__main__":
     test_job()

获取输出为:

Traceback (most recent call last):
 File "C:/Python_Projects/Test/com/xyz/ds/ds_schedular.py", line 9, in <module>
test_job()
 File "C:/Python_Projects/Test/com/xyz/ds/ds_schedular.py", line 5, in test_job
testobj = tp.test_funct()
AttributeError: module 'TestDir.TestSubDirFile' has no attribute 'test_funct'

根据你的目录结构

ds_scheduler.py
TestDir -- 目录名称
- TestSubDirFile.py - Python 文件名

TestSubDirFile.py 文件中,您定义了 class 名称为 TestSubDirFile.

from TestDir import TestSubDirFile as tp

根据您上面的导入声明,您只能访问 py 文件。

要在 class 中访问 test_func() 方法,您需要按照以下步骤操作。

tsdf = tp.TestSubDirFile() tsdf.test_funct()

希望对您有所帮助