[英]How to declare a variable to be used by the imported module
我有一個名為my_module.py
的模塊,在此模塊內有一個函數my_function
:
def myFunction():
print my_variable
顯然,當調用此函數時,它會打印my_variable
,該my_variable
尚未在任何地方實例化。 因此,從模塊本身內部調用myFunction()
將使執行崩潰。
現在,除了my_module.py
外,我還有另一個名稱為my_app.py
腳本位於同一文件夾中。
在my_app.py
內部,我要導入my_module.py
並在其命名空間下實例化my_variable
。 實例化my_variable
之后,我將調用my_module.myFunction()
,它拾取my_variable
並打印其上下文:
import module
module.my_variable = 'this variable is instantiated inside of another script'
module.myFunction()
雖然這種方法有效,但我想知道它是否設計正確。 有沒有其他的方式來實例化之外的變量imported module
被這個使用imported module
?
import module
module.my_variable = 'this variable is instantiated inside of another script'
module.myFunction()
雖然這種方法有效,但我想知道它是否設計正確。
不,這是設計不當的。 一種正確的方法是將值顯式傳遞給函數。
還有其他方法可以在導入模塊之外實例化該導入模塊要使用的變量嗎?
聲明此變量只是另一個模塊。 例如my_vars.py
:
my_variable = 'this variable is instantiated inside of another script'
然后在my_module.py
:
import my_vars
def myFunction():
print my_vars.my_variable
我不確定您要實現什么目標,但是通常最好的做法是不對“全局”變量進行突變。 每次您想要在代碼中使用my_function()
,都必須先顯式更改my_variable
,如果其他函數/方法依賴於它,則會在代碼中觸發副作用。 最好的方法是重寫my_function()
,使其接受my_variable
作為參數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.