0

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

蟒蛇代码:

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'
4

1 回答 1

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还不存在,这就中断了。

于 2013-05-03T17:09:37.127 回答