2017-09-03 133 views
1

我有一个带有n个参数的方法。我想所有的默认参数值设置为None,例如:如何将所有默认参数值一次设置为无

def x(a=None,b=None,c=None.......z=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 

但是这样你将失去自省的功能,因为您手动更改签名。

但我怀疑可能有更好的方法来解决问题或完全避免问题。

相关问题