[英]How to pass a function as argument to another function and use the value returned by that function in python?
我试图否定一个函数返回的值。
认为代码是
def greater(a,b):
return a>b
check = negate(greater)
assert check(8,9)
要么
def equal(a,b):
return a==b
check = negate(equal)
assert check("python","java")
我应该如何定义NEGATE函数???
使用函数样式的装饰器 :
def negate(func):
def inner(*args, **kwargs):
val = func(*args, **kwargs)
return not val
return inner
演示:
>>> greater(10, 20)
False
>>> negate(greater)(10, 20)
True
为了维护之类的docstring
和传递功能的其他属性来negate
你可以使用functools.wraps
。
from functools import wraps
def negate(func):
@wraps(func)
def inner(*args, **kwargs):
val = func(*args, **kwargs)
return not val
return inner
像这样:
def negate(func):
def result(*args):
return not func(*args)
return result
这个函数创建一个函数,该函数返回调用原始函数而not
返回其返回值,然后返回该函数的结果。
在装饰器中使用not
运算符:
from functools import wraps
def negate(func):
@wraps(func)
def wrapper(*args, **kw):
return not func(*args, **kw)
return wrapper
上面的装饰器返回一个包装函数,该包装函数not
用于该包装函数的返回值。 上面的示例中的@functools.wraps()
装饰器是可选的,但可确保包装器从原始函数中获取docstring和其他可自省的属性,使其行为与包装后的函数更接近。
演示:
>>> from functools import wraps
>>> def negate(func):
... @wraps(func)
... def wrapper(*args, **kw):
... return not func(*args, **kw)
... return wrapper
...
>>> def greater(a,b):
... return a>b
...
>>> check = negate(greater)
>>> check(8, 9)
True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.