我是Python新手,如果在編寫此問題時沒有使用適當的白話,我表示歉意。我在Windows機器上使用Python 3.6.1。我提供了我遇到的問題的一個工作示例。加載具有相關類的模塊
假設我寫了一個保存在Demo_func.py文件中的模塊。它包含以下功能:
def chebyshev_nodes(degree, domain):
return Chebyshev.basis(degree,domain).roots()
我然後運行下面的腳本:如果不是我寫我的腳本中的函數chebyshev_nodes
NameError: name 'Chebyshev' is not defined
:
from numpy.polynomial.chebyshev import Chebyshev
from Demo_func import chebyshev_nodes
chebyshev_nodes(5, [1,5])
它產生這個錯誤下面,那麼它工作得很好。
from numpy.polynomial.chebyshev import Chebyshev
def chebyshev_nodes(degree, domain):
return Chebyshev.basis(degree,domain).roots()
chebyshev_nodes(5, [1,5])
我的理解是,進口的切比雪夫是全球性的。但不知何故,它在我的模塊Demo_func中運行。我如何編寫一個依賴於Chebyshev類的模塊?
「我的理解是,進口切比雪夫是全球性的」 - 事實並非如此。它執行的模塊初始化是全局性的,但它只會使'Chebyshev'名稱可用於執行導入的範圍。 – user2357112
謝謝,這很有幫助。在函數定義中導入Chebyshev。這是做到這一點的正確方法嗎? –