我试图创建一个函数,当导入并调用时,它将检查并修改一个元组。我希望能多次拨打这个电话。但是,我只是让函数返回新的变量,因为我想不出一种方法来就地更改变量。你知道吗
以下是我的两个文件示例,我希望它如何工作:
**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设置文件的中间件的函数。另外,我没有在不同的文件上使用该函数,但我也认为这应该是可能的。你知道吗
我看不出你现在做的有什么不对(最后一个代码块),很明显。如果我看到这样的东西:
我知道tuple已经更改了(可能只是示例中使用的一个名称,但不要将变量称为“tuple”)。你知道吗
但如果我看到这个(你想做的):
我从没想过
function
会改变tuple
的值。总之,可以通过以下方式完成:也可以这样做:
我会说这更好一点,因为如果我使用你的代码有问题,我可能会猜
function
对元组做了一些事情。你知道吗代码是:
最后我要说的是,你现在所做的很清楚,也很简单,我不会改变它。
这似乎奏效了:
相关问题 更多 >
编程相关推荐