Python: getting a reference to a function from inside itself

心已入冬 提交于 2019-12-03 09:54:59

The same way, just use its name.

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

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]

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

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