8

関数を呼び出す Python スクリプトを作成しました。この関数は、次のように、関数内のパラメーターとして 7 つのリストを受け取ります。

def WorkDetails(link, AllcurrValFound_bse, AllyearlyHLFound_bse, 
                AlldaysHLFound_bse, AllvolumeFound_bse, 
                AllprevCloseFound_bse, AllchangePercentFound_bse, 
                AllmarketCapFound_bse):

を除くすべての引数linkはリストです。しかし、これにより、私のコードはかなり見苦しくなります。関数はこれらすべてのリストにいくつかの値を追加するため、これらのリストをこの関数に渡します。他のユーザーにとってより読みやすい方法で行うにはどうすればよいですか?

4

6 に答える 6

5

次のように変更できます。

def WorkDetails(link, details):

次に、次のように呼び出します。

details = [ AllcurrValFound_bse, AllyearlyHLFound_bse, 
            AlldaysHLFound_bse, AllvolumeFound_bse, 
            AllprevCloseFound_bse, AllchangePercentFound_bse, 
            AllmarketCapFound_bse ]
workDetails(link, details)

そして、次のようにして、詳細からさまざまな値を取得します。

AllcurrValFound_bse = details[0]
AllyearlyHLFound_bse = details[1]
...

変数名をキーとしてディクショナリに変換する方がより堅牢になるdetailsため、数行のコードと防御的なプログラミングの間で選択してください =p

于 2012-11-25T16:26:06.667 に答える
2

*argsリストに名前を使用する必要がない場合は、次を使用できます。

def WorkDetails(link, *args):
    if args[0] == ... # Same as if AllcurrValFound_bse == ...
        ...

 # Call the function:
 WorkDetails(link, AllcurrValFound_bse, AllyearlyHLFound_bse, AlldaysHLFound_bse, AllvolumeFound_bse, AllprevCloseFound_bse, AllchangePercentFound_bse, AllmarketCapFound_bs)

または、辞書を使用することもできます

def WorkDetails(link, dict_of_lists):
    if dict_of_lists["AllcurrValFound_bse"] == ...
        ...

# Call the function
myLists = {
    "AllcurrValFound_bse": AllcurrValFound_bse,
    "AllyearlyHLFound_bse": AllyearlyHLFound_bse,
    ...,
    ...
}
WorkDetails(link, myLists)
于 2012-11-25T16:25:30.293 に答える
1

I think that usage of **kwarg is better. Look this example:

def MyFunc(**kwargs):
    print kwargs


MyFunc(par1=[1],par2=[2],par3=[1,2,3])
于 2012-11-25T18:50:46.490 に答える