Python: getting a reference to a function from inside itself

后端 未结 3 2130
小鲜肉
小鲜肉 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

提交回复
热议问题