【问题标题】:can't access imported functions in Python无法在 Python 中访问导入的函数
【发布时间】:2011-07-29 19:00:33
【问题描述】:

谁能帮我解决这个问题?

我将继续使用 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!

这是怎么回事??

【问题讨论】:

    标签: python import pydev aptana


    【解决方案1】:

    您错过了testMod 模块。你方法的全称是testModule.testMod.test

    【讨论】:

    • 具体来说,单独的testMod 仅指__init__.py(可用于轻松提供整个包API 的有限但有用的子集)。
    【解决方案2】:

    嗯,这基本上是因为testModule 中没有方法test()。其实你的testModule不是模块,而是一个包,而testModtestModule包中的一个模块。

    因此,对于您的结构,以下内容将起作用:

    from testModule import testMod
    testMod.test(4) 
    

    详情请见http://docs.python.org/tutorial/modules.html

    【讨论】:

    • 我不同意这一点。一个包就是一个包。包是作为模块集合的特定目录,在这种情况下就是这样。可能有人会说__init__ 是一个模块(虽然我不会),但对于 testModule - 通常不会将 testModule 称为模块。有关术语,请参阅docs.python.org/tutorial/modules.html#packages。由于__init__ 将内容加载到testModule 命名空间中,Python 将包视为模块这一事实并不意味着它不是包,对吧?
    • 这变得令人困惑......我的基本直觉是 Module 是函数 def 等的集合。我们定义用于特殊项目。如果我们想要有相同名称的不同模块,我们定义包,因此不同包下的一个模块不相同,但名称相似,因为它们所做的想法是相同的。
    猜你喜欢
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-02
    • 1970-01-01
    相关资源
    最近更新 更多