2017-09-03 3 views
1

私はn個のパラメータを持つメソッドを持っています。私は、例えば、Noneにすべてのデフォルトパラメータ値を設定したい。:すべてのデフォルトパラメータ値をNoneに一度に設定する方法

def x(a=None,b=None,c=None.......z=None): 

はメソッドを記述しながら、彼らはNoneにデフォルト設定されていない場合は、一度なしにすべてのパラメータ値を設定する方法で構築された任意のはありますか?

+0

うん、たくさんの方法それを達成するが、すべてが「不利」のいくつかの並べ替えが付属していますが、おそらくある(そうしない、少なくとも場合IDEレベルで行う)、例えば、それはイントロスペクションを真剣に制限する可能性があります。 – MSeifert

+0

私の知る限りではありませんが、あなたはそれを処理するデコレータを書くことができます – Pythonist

+0

私の質問はこの質問からですhttps://stackoverflow.com/questions/46025154/how-to-pass-pandas-dataframe-columns-as- kwargs/46025394#46025394私は何度も何も書かなければなりませんでした。それで簡単なやり方は? – Dark

答えて

3

、あなたは__defaults__設定することができます。

def foo(a, b, c, d): 
    print (a, b, c, d) 

# foo.__code__.co_varnames is ('a', 'b', 'c', 'd') 
foo.__defaults__ = tuple(None for name in foo.__code__.co_varnames) 

foo(b=4, d=3) # prints (None, 4, None, 3) 
+0

私はそれには私はそれを機能させるために関数を再コンパイルしなければならないと思った。それはかなり賢いです。 – MSeifert

2

文字どおり、すべての引数にデフォルトでNoneを追加する場合は、デコレータのアプローチが必要です。それは、Python 3についてのみだ場合、inspect.signatureを使用することができます:

def function_arguments_default_to_None(func): 
    # Get the current function signature 
    sig = inspect.signature(func) 
    # Create a list of the parameters with an default of None but otherwise 
    # identical to the original parameters 
    newparams = [param.replace(default=None) for param in sig.parameters.values()] 
    # Create a new signature based on the parameters with "None" default. 
    newsig = sig.replace(parameters=newparams) 
    def inner(*args, **kwargs): 
     # Bind the passed in arguments (positional and named) to the changed 
     # signature and pass them into the function. 
     arguments = newsig.bind(*args, **kwargs) 
     arguments.apply_defaults() 
     return func(**arguments.arguments) 
    return inner 


@function_arguments_default_to_None 
def x(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z): 
    print(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z) 

x() 
# None None None None None None None None None None None None None None 
# None None None None None None None None None None None None 

x(2) 
# 2 None None None None None None None None None None None None None 
# None None None None None None None None None None None None 

x(q=3) 
# None None None None None None None None None None None None None None 
# None None 3 None None None None None None None None None 

手動で署名を変更するので、その方法は、あなたが機能するためにイントロスペクションを失うことになるが。

しかし、おそらく、問題を解決するか、問題を完全に回避する方が良いと思われます。

プレーン機能については
関連する問題