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?
In Python, it's also possible for a function to call itself! A function that calls itself is said to be recursive, and the technique of employing a recursive function is called recursion. It may seem peculiar for a function to call itself, but many types of programming problems are best expressed recursively.
Python also accepts function recursion, which means a defined function can call itself. Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.
Recursion is a programming term that means calling a function from itself. Recursive functions can be used to solve tasks in elegant ways. When a function calls itself, that's called a recursion step.
A function can refer to and call itself.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With