is there a way to change the return value of a function without changing the function's body?

时间:2016-04-04 16:32:38

标签: python

def f(x):
    return (x - 2)/2 
def g(x):
    return x

this code will do this:

func = g(f)

now func(1) = -1/2

what if I want to modify g(x) (and not f(x)) so that

func = g(f) 
func(1) = 1/2

is there a way to do this?

thank you Edit: f(x) can be any function that possibly returns a negative number

3 个答案:

答案 0 :(得分:4)

>>> def f(x):
...     return (x - 2)/2
...
>>> def g(function):
...     return lambda x: abs(function(x))
...
>>> func = g(f)
>>> func(1)
0.5

答案 1 :(得分:3)

You are looking for a function wrapping another function. This can be done in Python using decorators.

Given your function f(x), let's say you'd like to receive the negative function value. And f(x) might be any function with any number of arguments. And possibly you don't really know f(x) at all.

Python's standard library comes with functools.wraps, which can be really handy in this case:

def g(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        func_value = func(*args, **kwargs)
        return -func_value
    return wrapper

Now the function g(func) returns a wrapper wrapping func post-processing its output:

>>> new_func = g(f)  # your original f(x)
>>> print(new_func(1))
0.5

This works with any function func with any number of positional or keyword arguments.

答案 2 :(得分:1)

for a generic application :

def absfunc(f):
    def absf(*args):
        return abs(f(*args))
    return absf

@absfunc
def f(x) :return (x-2)/2

f(1) is now 0.5. You change the return value without changing the body neither the name.