我正在尝试创建一个函数,在导入然后调用它时,它将检查并修改元组。我想能够多次打电话。但是,我只是让函数返回新变量,因为我无法找到一种方法来改变变量。
以下是我的两个文件示例,我希望它能如何工作:
**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',)
这太麻烦了。首先,我必须传入旧的元组值并获得返回值,而不是直接替换元组。它有效,但它不是DRY,我知道必须有一种方法可以使它更干净。
我无法使用列表,因为这实际上是在我的django设置文件中更新我的中间件的功能。此外,我不 将功能放在不同的文件上,但我也认为应该可以。
答案 0 :(得分:2)
我没有看到你现在正在做什么(最后一个代码块),这很清楚。如果我看到类似的东西:
tuple = # something ...
我知道元组已更改(可能它只是您用于示例的名称,但不要将变量称为“元组”)。
但如果我看到这个(你想做什么):
tuple = 'one', two'
function('add this')
我永远不会想象function
改变了tuple
的价值。无论如何,它可以通过以下方式完成:
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')
我会说它好一点,因为如果我使用你的代码有问题,我可能会猜测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')
最后我会说你现在正在做的事情是清楚而简单的,我不会改变它。