将函数负数作为n参数传递

时间:2019-04-01 11:57:26

标签: python python-3.x python-3.6 metaprogramming

在Python中,我可以将一个函数作为参数传递给另一个函数,即:

inspect.getmembers(random, callable)

这将使我得到random变量的所有可调用成员。 callable是传递给执行检查的函数(仅返回满足检查条件的变量成员)。

我的特定问题是如何获取所有不可调用的参数,更广泛地说,是否有一种方法可以将函数的“反向”作为参数传递?

我已经尝试过了:

inspect.getmembers(random, !callable)
inspect.getmembers(random, not callable)

第一个是语法错误,而第二个则无效。

作为一种解决方法,我定义了自己的函数:

def uncallable(object)
    return not callable(object)

因此可行:

inspect.getmembers(random, uncallable)

但是我想知道是否有更简单的解决方案。

2 个答案:

答案 0 :(得分:1)

只需使用lambda:

inspect.getmembers(random, lambda x: not callable(x))

答案 1 :(得分:0)

只需编写您无法调用的包装器即可。

我所知没有一种语言允许您期望的那种高级函数运算。

没有办法使这种概念大体上起作用。

这些函数的结果是什么?

! len
len + len
len + ! len

所以剩下的就是明确编写的高阶函数,以函数为参数并返回诸如此类的其他函数的akka​​函数

def negate(func):
    def wrapped(*args, **kwargs):
        return not func(*args, **kwargs)
    return wrapped

uncallable = negate(callable)

这些与python装饰器的模式相同。

相关问题