![](/img/trans.png)
[英]Python lambda used as an argument, calling other arguments from parent function
[英]Python specify lambda arguments as a function argument
是否有可能指定作为函数参数的lambda可以接受多少个参数?
例如:
def func(k=lambda x:return x**2):
return k
如果k不是标准的lambda,我可以指定k应该只接受一个参数吗?
最高
您可以使用inspect.getargspec
做这样的事情:
import inspect
def func (k = lambda x: x ** 2):
if not callable(k) or len(inspect.getargspec(k).args) != 1:
raise TypeError('k must take exactly one argument.')
# Do whatever you want
请注意,上述操作会因类似(但不应)而失败:
func (lambda x, y = 8: x + y)
...因此,如果要处理这种情况,您将需要一些更复杂的东西:
import inspect
def func (k = lambda x: x ** 2):
if not callable(k):
raise TypeError('k must be callable.')
argspec = inspect.getfullargspec(k)
nargs = len(argspec.args)
ndeft = 0 if argspec.defaults is None else len(argspec.defaults)
if nargs != ndeft + 1:
raise TypeError('k must be callable with one argument.')
# Do whatever you want
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.