簡體   English   中英

在python中使用導入命令時出錯

[英]error when using import command in python

我是python的新手,現在學習如何導入模塊或函數,但是出現了這些已發布的錯誤。 python代碼以以下名稱保存: hello_module.py

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'

您不能也不應導入自己的模塊。 您在當前名稱空間中定義了hello_func ,只需直接使用它即可。

您可以將函數放在單獨的文件中,然后導入該文件:

  • 文件foo.py

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

     import foo foo.hello_func() 

並運行bar.py作為腳本。

如果您嘗試導入自己的模塊,它會重新導入自己 ,當你做,你導入一個不完整的模塊。 它尚未設置屬性,因此hello_module.hello_func尚不存在,並且中斷了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM