Monday, November 18, 2024
Google search engine
HomeLanguagesReturning a function from a function – Python

Returning a function from a function – Python

Functions in Python are first-class objects. First-class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures.

Properties of first-class functions:

  • A function is an instance of the Object type.
  • You can store the function in a variable.
  • You can pass the function as a parameter to another function.
  • You can return the function from a function.
  • You can store them in data structures such as hash tables, lists, …

Example 1: Functions without arguments

In this example, the first method is A() and the second method is B(). A() method returns the B() method that is kept as an object with name returned_function and will be used for calling the second method.

Python3




# define two methods
 
# second method that will be returned
# by first method
def B():
    print("Inside the method B.")
     
# first method that return second method
def A():
    print("Inside the method A.")
     
    # return second method
    return B
 
# form a object of first method
# i.e; second method
returned_function = A()
 
# call second method by first method
returned_function()


Output :

Inside the method A.
Inside the method B.

Example 2: Functions with arguments

In this example, the first method is A() and the second method is B(). Here A() method is called which returns the B() method i.e; executes both the functions.

Python3




# define two methods
 
# second method that will be returned
# by first method
def B(st2):
    print("Good " + st2 + ".")
     
# first method that return second method
def A(st1, st2):
    print(st1 + " and ", end = "")
     
    # return second method
    return B(st2)
 
# call first method that do two work:
# 1. execute the body of first method, and
# 2. execute the body of second method as
#    first method return the second method
A("Hello", "Morning")


Output :

Hello and Good Morning.

Example 3: Functions with lambda

In this example, the first method is A() and the second method is unnamed i.e; with lambda. A() method returns the lambda statement method that is kept as an object with the name returned_function and will be used for calling the second method.

Python3




# first method that return second method
def A(u, v):
    w = u + v
    z = u - v
     
    # return second method without name
    return lambda: print(w * z)
 
# form a object of first method
# i.e; second method
returned_function = A(5, 2)
 
# check object
print(returned_function)
 
# call second method by first method
returned_function()


Output :

<function A.<locals>.<lambda> at 0x7f65d8e17158>
21

RELATED ARTICLES

Most Popular

Recent Comments