2012-01-25 40 views
2

我想創建一個函數,當導入並調用它時,它將檢查和修改一個元組。我希望能夠多次調用這個。但是,我只是讓函數返回新變量,因爲我無法找到一種方法來更改變量。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設置文件上更新我的中間件的函數。我也沒有在不同的文件上有功能,但我也認爲它應該是可能的。

+0

你有沒有試過第一個區塊的代碼? –

+0

您無法修改元組。 – wim

+0

你有一個循環導入 – wim

回答

2

我看不出有什麼錯,你現在(最後一個代碼塊)在做什麼,很明顯。如果我看到這樣的:

tuple = # something ... 

我知道,元組發生變化(可能它只是你使用的例如名稱,但不要打電話給你的變量「元組」)。

但如果我看到這個(你想要做什麼):

tuple = 'one', two' 
function('add this') 

我從來沒有想象function改變tuple THA值。無論如何,它可以用做:

tuple = 'one', 'two' 

def function(string): 
    global tuple 
    if new_string not in tuple: 
     tuple = (new_string,) + tuple 

function('add this') 

而且這樣的事情可以做:

tuple = 'one', two' 
function(tuple, 'add this') 

我會說這是一個好一點,因爲如果我是使用具有代碼probelms我可能猜測function做了一些元組。

,代碼爲:

tuple = 'one', 'two' 

def function(old_tuple, string): 
    global tuple 
    if new_string not in old_tuple: 
     tuple = (new_string,) + old_tuple 

function(tuple, 'add this') 

最後我會說,你現在在做什麼是明確的,更簡單,我不會改變它。

+0

你在那裏的最後一個代碼塊是我想要的,但是我也希望該函數在一個單獨的文件中,而不是元組和函數的調用。當我在那裏做什麼時,它會使用該函數更改文件中的元組,但是它在調用函數後不會保留編輯後的版本,即在元組文件中調用元組的文件時。 –

+0

其實我認爲你是對的,我有更好的。更清晰。我仍然很好奇,如果其他方式是可能的,但。 –

+1

@saul.shanabrook:是的,更清楚的是,除非你真的被迫使用全局的參數,否則應該將參數作爲參數傳遞:)出於好奇,我不得不說,你試圖使用兩個文件做什麼會以循環導入結束,因此出現錯誤。 –

1

這似乎工作:

def function(new_string): 
if new_string not in variable.tuple: 
    variable.tuple = (new_string,) + variable.tuple 
+0

如果它們在同一個文件中,它可以工作。如果他們不是這樣做的話。 [其他答案](http://stackoverflow.com/a/9000442/907060)解釋得很好。 –