2013-05-03 56 views
0

我是python新手,现在正在学习如何导入模块或函数,但是我收到了这些发布的错误。在Python代码保存名下:hello_module.py在Python中使用导入命令时出错

Python代码:

def hello_func(): 
    print ("Hello, World!") 
hello_func() 
import hello_module 
hello_module.hello_func() 

错误消息:

Traceback (most recent call last): 
    File "C:/Python33/hello_module.py", line 9, in <module> 
    import hello_module 
    File "C:/Python33\hello_module.py", line 10, in <module> 
    hello_module.hello_func() 
AttributeError: 'module' object has no attribute 'hello_func' 
+1

import hello_module不应该在hello_module.py中。它没有任何意义。 – njzk2 2013-05-03 17:27:48

回答

4

你不能,不应该导入自己的模块。您在目前的名称空间中定义了hello_func,只是直接使用它。

你可以把功能在单独文件,然后导入:

  • 文件foo.py

    def def hello_func(): 
        print ("Hello, World!") 
    
  • 文件bar.py

    import foo 
    
    foo.hello_func() 
    

并运行bar.py作为脚本。

如果您尝试导入自己的模块,它会导入本身再次,当你做,你导入一个不完整的模块。它不会有它的属性设置,所以hello_module.hello_func还不存在,并打破。