我有一个带n个参数的方法。我想将所有默认参数值设置为None
,例如:
def x(a=None,b=None,c=None.......z=None):
如果在编写方法时未将默认值设置为None,是否有任何内置方法可以将所有参数值一次性设置为None?
答案 0 :(得分:4)
对于普通功能,您可以设置__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)
答案 1 :(得分: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
然而,通过这种方式,您将失去对该功能的内省,因为您手动更改了签名。
但我怀疑可能有更好的方法来解决问题或完全避免问题。