Python: getting a reference to a function from inside itself

后端 未结 3 2091
小鲜肉
小鲜肉 2021-02-12 13:03

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=\"he         


        
相关标签:
3条回答
  • 2021-02-12 13:24

    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

    0 讨论(0)
  • 2021-02-12 13:29

    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]
    
    0 讨论(0)
  • 2021-02-12 13:42

    The same way, just use its name.

    >>> def g(x):
    ...   g.r = 4
    ...
    >>> g
    <function g at 0x0100AD68>
    >>> g(3)
    >>> g.r
    4
    
    0 讨论(0)
提交回复
热议问题