Python:从自身内部获取对函数的引用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/852401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:59:17  来源:igfitidea点击:

Python: getting a reference to a function from inside itself

pythonfunctionself-reference

提问by Ram Rachum

If I define a function:

如果我定义一个函数:

def f(x):
    return x+3

I can later store objects as attributes of the function, like so:

我以后可以将对象存储为函数的属性,如下所示:

f.thing="hello!"

I would like to do this from inside the code of the function itself. Problem is, how do I get a reference to the function from inside itself?

我想从函数本身的代码内部执行此操作。问题是,如何从内部获取对函数的引用?

采纳答案by SurDin

The same way, just use its name.

同样的方法,只需使用它的名字。

>>> def g(x):
...   g.r = 4
...
>>> g
<function g at 0x0100AD68>
>>> g(3)
>>> g.r
4

回答by Jeff Ober

If you are trying to do memoization, you can use a dictionary as a default parameter:

如果您尝试进行记忆,可以使用字典作为默认参数:

def f(x, memo={}):
  if x not in memo:
    memo[x] = x + 3
  return memo[x]

回答by Jeff Ober

Or use a closure:

或者使用闭包:

def gen_f():
    memo = dict()
    def f(x):
        try:
            return memo[x]
        except KeyError:
            memo[x] = x + 3
    return f
f = gen_f()
f(123)

Somewhat nicer IMHO

稍微好一点恕我直言