[英]How to pass a function as argument to another function and use the value returned by that function in python?
I am trying to negate the value returned by one function. 我试图否定一个函数返回的值。
Consider the code to be 认为代码是
def greater(a,b):
return a>b
check = negate(greater)
assert check(8,9)
OR 要么
def equal(a,b):
return a==b
check = negate(equal)
assert check("python","java")
How should I define the NEGATE function??? 我应该如何定义NEGATE函数???
Use a function-style decorator : 使用函数样式的装饰器 :
def negate(func):
def inner(*args, **kwargs):
val = func(*args, **kwargs)
return not val
return inner
Demo: 演示:
>>> greater(10, 20)
False
>>> negate(greater)(10, 20)
True
To preserve things like docstring
and other attributes of the function being passed to negate
you can use functools.wraps
. 为了维护之类的
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
Like this: 像这样:
def negate(func):
def result(*args):
return not func(*args)
return result
This is a function which creates a function which returns the result of invoking the original function and not
ing it's return value, and then returning that function. 这个函数创建一个函数,该函数返回调用原始函数而
not
返回其返回值,然后返回该函数的结果。
Use the not
operator in a decorator: 在装饰器中使用
not
运算符:
from functools import wraps
def negate(func):
@wraps(func)
def wrapper(*args, **kw):
return not func(*args, **kw)
return wrapper
The above decorator returns a wrapper function that applies not
to the return value of the wrapped function. 上面的装饰器返回一个包装函数,该包装函数
not
用于该包装函数的返回值。 The @functools.wraps()
decorator in the above example is optional but makes sure the wrapper gains the docstring and other introspectable attributes from the original function, making it behave more closely like the wrapped function. 上面的示例中的
@functools.wraps()
装饰器是可选的,但可确保包装器从原始函数中获取docstring和其他可自省的属性,使其行为与包装后的函数更接近。
Demo: 演示:
>>> 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.