首頁  >  文章  >  後端開發  >  為什麼會出現「AttributeError: \'module\' object has no attribute [duplicate]\」?

為什麼會出現「AttributeError: \'module\' object has no attribute [duplicate]\」?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-20 12:55:02732瀏覽

Why does

“AttributeError: 'module' object has no attribute [duplicate]”:綜合指南

當Python 模組嘗試此時會發生錯誤訪問不存在的屬性。在您的具體情況下,錯誤是“AttributeError:'module'物件沒有屬性'hi'”。此錯誤表示您正在匯入的模組 (b.py) 沒有名為「hi」的函數。

了解相互頂級導入

出現此問題是因為 a.py 和 b.py 之間存在相互頂級導入。通常不建議這樣做,因為它可能會導致循環導入和其他問題。

解決問題

要修復此錯誤並避免相互導入,您可以導入函數內的模組如下:

在b. py 中:

<code class="python">def cause_a_to_do_something():
    import a
    a.do_something()</code>

在a.py 中:

<code class="python">import b

def hello():
    print("hello")

print("a.py")
print(hello())
b.cause_a_to_do_something()</code>

這樣,a.py 就可以安全地導入b.py 並呼叫其函數,而不會導致任何錯誤。

導入最佳化

雖然看起來效率不高在函數中導入,但實際上不是。 Python 會快取導入的模組,因此導入操作僅在第一次呼叫該函數時執行。隨後的導入是一個快速的操作。

以上是為什麼會出現「AttributeError: \'module\' object has no attribute [duplicate]\」?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn