python - can function call itself without explicitly using name?

  • Last Update :
  • Techknowledgy :

I found a simple, working solution.

from functools
import wraps

def recfun(f):
def _f( * a, ** kwa): return f(_f, * a, ** kwa)
return _f

# it 's a decorator, so a separate class+method don'
t need to be defined
for each
function and the class does not need to be instantiated,
# as with Alex Hall 's answer
def fact(self, n):
   if n > 0:
   return n * self(n - 1) # doesn 't need to be self(self, n-1),
# as with lkraider 's answer
   return 1

print(fact(10)) # works, as opposed to dursk 's answer

Here's an (untested) idea:

class Foo(object):

   def __call__(self, * args):
   # do stuff
   self( * other_args)

You can bind the function to itself, so it receives a reference to itself as first parameter, just like self in a bound method:

def bind(f):
"Decorate function `f` to pass a reference to the function
as the first argument ""
return f.__get__(f, type(f))

def foo(self, x):
   "This is a bound function!"
print(self, x)

I don't know why you'd want to do this, but nonetheless, you can use a decorator to achieve this.

def recursive_function(func):
   def decorator( * args, ** kwargs):
   return func( * args, my_func = func, ** kwargs):
      return decorator

And then your function would look like:

def my_recursive_function(my_func = None):

disclaimer: dirty solution but no decorator needed

import sys

def factorial(x):
   _f = eval(sys._getframe().f_code.co_name)
return x
if x < 3
else x * _f(x - 1)


Suggestion : 2

The situation when function calls itself is called recursion, and such function is called recursive. ,Recursive functions are powerful mechanism in programming. Unfortunately, they are not always effective and often lead to mistakes. The most common error is infinite recursion, when the chain of function calls never ends (well, actually, it ends when you run out of free memory in your computer). An example of infinite recursion: ,Therefore, when coding a recursive function, it is first necessary to ensure it will reach its stopping conditions — to think why your recursion will ever end. ,Recursive call with incorrect parameters. For example, if the function factorial(n) calls the function factorial(n), we will also obtain an infinite chain of calls.

# compute 3!
   res = 1
for i in range(1, 4):
   res *= i

# compute 5!
   res = 1
for i in range(1, 6):
   res *= i
def factorial(n):
   res = 1
for i in range(1, n + 1):
   res *= i
return res

def max(a, b):
   if a > b:
   return a
   return b

print(max(3, 5))
print(max(5, 3))
print(max(int(input()), int(input())))
def max(a, b):
   if a > b:
   return a
   return b

def max3(a, b, c):
   return max(max(a, b), c)

print(max3(3, 5, 4))
def max( * a):
   res = a[0]
for val in a[1: ]:
   if val > res:
   res = val
return res

print(max(3, 5, 4))
def f():

a = 1

Suggestion : 3

Often, the first argument of a method is called self. This is nothing more than a convention: the name self has absolutely no special meaning to Python. Note, however, that by not following the convention your code may be less readable to other Python programmers, and it is also conceivable that a class browser program might be written that relies upon such a convention.,Note that the mangling rules are designed mostly to avoid accidents; it still is possible to access or modify a variable that is considered private. This can even be useful in special circumstances, such as in the debugger.,In practice, the statements inside a class definition will usually be function definitions, but other statements are allowed, and sometimes useful — we’ll come back to this later. The function definitions inside a class normally have a peculiar form of argument list, dictated by the calling conventions for methods — again, this is explained later.,The name BaseClassName must be defined in a scope containing the derived class definition. In place of a base class name, other arbitrary expressions are also allowed. This can be useful, for example, when the base class is defined in another module:

def scope_test():
   def do_local():
   spam = "local spam"

def do_nonlocal():
   nonlocal spam
spam = "nonlocal spam"

def do_global():
   global spam
spam = "global spam"

spam = "test spam"
print("After local assignment:", spam)
print("After nonlocal assignment:", spam)
print("After global assignment:", spam)

print("In global scope:", spam)
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam
class ClassName:
class MyClass:
"A simple example class"
i = 12345

def f(self):
   return 'hello world'
x = MyClass()
def __init__(self): = []

Suggestion : 4

In Python, we know that a function can call other functions. It is even possible for the function to call itself. These types of construct are termed as recursive functions.,Every recursive function must have a base condition that stops the recursion or else the function calls itself infinitely., In this tutorial, you will learn to create a recursive function (a function that calls itself).,Each function multiplies the number with the factorial of the number below it until it is equal to one. This recursive call can be explained in the following steps.

Example of a recursive function

def factorial(x):
"This is a recursive function
to find the factorial of an integer ""

if x == 1:
   return 1
   return (x * factorial(x - 1))

num = 3
print("The factorial of", num, "is", factorial(num))


The factorial of 3 is 6

Each function multiplies the number with the factorial of the number below it until it is equal to one. This recursive call can be explained in the following steps.

factorial(3) # 1 st call with 3
3 * factorial(2) # 2n d call with 2
3 * 2 * factorial(1) # 3 rd call with 1
3 * 2 * 1 #
return from 3 rd call as number = 1
3 * 2 #
return from 2n d call
6 #
return from 1 st call