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
def B():
print ( "Inside the method B." )
def A():
print ( "Inside the method A." )
return B
returned_function = A()
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
def B(st2):
print ( "Good " + st2 + "." )
def A(st1, st2):
print (st1 + " and " , end = "")
return B(st2)
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
def A(u, v):
w = u + v
z = u - v
return lambda : print (w * z)
returned_function = A( 5 , 2 )
print (returned_function)
returned_function()
|
Output :
<function A.<locals>.<lambda> at 0x7f65d8e17158>
21
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!