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

时间:2023-01-11 01:43:17

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?

我想从函数本身的代码中做到这一点。问题是,如何从内部获取对函数的引用?

3 个解决方案

#1


19  

The same way, just use its name.

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

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

#2


3  

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

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

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

#3


2  

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

哇有点好

#1


19  

The same way, just use its name.

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

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

#2


3  

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

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

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

#3


2  

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

哇有点好