代码之家  ›  专栏  ›  技术社区  ›  Manvi

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

  •  1
  • Manvi  · 技术社区  · 6 年前

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

    enter image description here

    测试目录。 初始化 .py包含:

    from . import TestSubDirFile
    

    TestDir.TestSubDirFile.py包含:

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

    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 回复  |  直到 6 年前
        1
  •  1
  •   rushikesh.meharwade    6 年前



    ds\ U调度程序.py

    -TestSubDirFile.py-Python文件名

    用名称定义类的文件 .

    from TestDir import TestSubDirFile as tp

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

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

    希望这有帮助