无法访问Python中导入的函数

4 投票
2 回答
10607 浏览
提问于 2025-04-16 22:32

有没有人能帮我一下?

我正在使用PyDev Aptana来开发Python代码。下面是我在PyDev IDE中的项目结构:

/testProject
        /src
            /testModule  
            __init__.py
            testMod.py
        main.py

testMod.py文件:

def test(n): 
    print "echo"+n 

main.py文件:

import testModule
testModule.test(4) 

当我尝试在PyDev中运行这个时,在main.py的第2行(也就是调用test(4)的地方)出现了这个错误:

AttributeError: 'module' object has no attribute 'test'

我把main.py改成了:

import testModule.test
testModule.test(4)  

但还是出现错误 'module' object not callable!

这到底是怎么回事呢?

2 个回答

8

你漏掉了 testMod 这个模块。你的方法的完整名称是 testModule.testMod.test

4

其实,这个问题的原因是因为在 testModule 里面没有 test() 这个方法。实际上,你的 testModule 不是一个模块,而是一个包,而 testMod 才是 testModule 包里面的一个模块。

所以,按照你现在的结构,下面的代码是可以正常工作的:

from testModule import testMod
testMod.test(4) 

想了解更多细节,可以查看 http://docs.python.org/tutorial/modules.html

撰写回答