2

インポートしてから呼び出すと、タプルをチェックして変更する関数を作成しようとしています。これを複数回呼び出すことができるようにしたいと思います。ただし、変数をその場で変更する方法がわからないため、関数に新しい変数を返すだけです。

2 つのファイルを使用した例を次に示します。

**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 設定ファイルでミドルウェアを更新する機能であるため、リストを使用できません。また、別のファイルに機能を持たせる必要はありませんが、可能だと思います。

4

2 に答える 2

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')

最後に、あなたが今していることは明確でシンプルであり、それを変えるつもりはありません。

于 2012-01-25T09:37:48.933 に答える
1

これはうまくいくようです:

def function(new_string):
if new_string not in variable.tuple:
    variable.tuple = (new_string,) + variable.tuple
于 2012-01-25T05:04:46.930 に答える