Function restriction by fixing an argument

纵饮孤独 提交于 2020-01-13 11:45:10

问题


How should I make function with lesser dimensionality than the original one by fixing an argument of it:

For example I want to make successor function out of sum function as follows:

def add(x,y):
    return x+y

Now I am looking for something like this:

g=f(~,1) which would be the successor function, i.e. g(x)=x+1.


回答1:


You can write your own function:

def g(y):
    return f(2, y)

Or more concisely:

g = lambda y: f(2, y)

There's also functools.partial:

import functools

def f(x, y):
    return x + y

g = functools.partial(f, 2)

You can then call it as before:

>>> g(3)
5



回答2:


If you do more than a little of this then you could use something like a decorator.

def with_x(x, fn, name=None):
  def foo(*args, **kwargs):
    return fn(x, *args, **kwargs)
  if name:
    foo.__name__ = name
return foo

def example(x,y):
  return x**y

g = with_x(2, example)

g(3)  #8

Use name = parameter if you care about the __name__ of the resulting function. You could get fancier with other hacks into the enclosed function innards possibly using the __inspect__ module if need be. But then you have re-written the previously mentioned functools partial stuff just to avoid having to give keyword arguments.



来源:https://stackoverflow.com/questions/17159065/function-restriction-by-fixing-an-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!