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

时间:2018-09-24 19:59:21

标签: python-3.x class oop module subdirectory

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

enter image description here

TestDir。初始化。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'

1 个答案:

答案 0 :(得分:1)

根据您的目录结构

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

TestSubDirFile.py 文件中,您定义了名为 TestSubDirFile 的类。

from TestDir import TestSubDirFile as tp

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

要访问类中的test_func()方法,您需要执行以下步骤。

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

希望这会有所帮助