This is a follow-up question from this.
I want a class that handles a function that can update itself. This is a simplified example, but I still end up with an infinite recursion:
def f(x):
return x
class func:
def __init__(self, f):
self.f = f
def translate(self, c):
def f_(x):
return self.f(x + c)
self.f = f_
It works only once:
>>> myfunc = func(f)
>>> myfunc.f(1)
1
>>> myfunc.translate(5)
>>> myfunc(1)
...
RecursionError: maximum recursion depth exceeded
The problem is that self.f calls self.f, which would not happen if translate were defined outside of a class:
def translate(f, c):
def f_(x):
return f(x+c)
return f_
This works:
>>> f = translate(f, 5)
>>> f(1)
6
>>> f = translate(f,-5)
>>>f(1)
1
How can I make it work inside the class?