我想創建一個函數,當導入並調用它時,它將檢查和修改一個元組。我希望能夠多次調用這個。但是,我只是讓函數返回新變量,因爲我無法找到一種方法來更改變量。Python通過導入的函數更改修改
這裏是我的兩個文件,我怎麼想它的工作的例子:
**modifier.py**
import variable
def function(new_string):
if new_string not in variable.tuple:
variable.tuple = new_string, + variable.tuple
**variable.py**
import modifier
tuple = ('one','two',)
modifier.function('add this')
modifier.function('now this')
#--> tuple should now equal ('now this', 'add this', 'one', 'two',)
但是現在我必須這樣做:
**modifier.py**
def function(tuple_old, new_string):
if new_string not in tuple_old:
return new_string, + tuple_old
**variable.py**
import modifier
tuple = ('one','two',)
tuple = modifier.function(tuple, 'add this')
tuple = modifier.function(tuple, 'now this')
#--> tuple now equals ('now this', 'add this', 'one', 'two',)
這是很多混亂。首先,我必須傳入舊的元組值並獲取返回的值,而不是直接替換元組。它有效,但它不幹,我知道必須有一種方法來使這個更清潔。
我不能使用列表,因爲這實際上是一個在我的django設置文件上更新我的中間件的函數。我也沒有有在不同的文件上有功能,但我也認爲它應該是可能的。
你有沒有試過第一個區塊的代碼? –
您無法修改元組。 – wim
你有一個循環導入 – wim