Treat function as first-class object
In Python both functions and classes are treated as objects which are called as first class objects, allowing them to be manipulated in the same ways as built-in data type. First class objects can be stored as data structures, as some parameters of some other functions, as control structure etc.. We can say that a function in Python is first class function if it supports all of the properties of a first class object.
Properties of first class function
- It is an instance of an object type.
- Functions can be stored as variable.
- Pass first class function as argument of some other functions.
- Return functions from other function.
- Store function in list, set or some other data structure.
1. Functions are objects
Python functions are first class objects. In Python a function can be assigned as variable. To assign it as variable, the function will not be called. So parentheses ( () ) will not be there.
In the example below, we are assigning function to a variable. This assignment doesn’t call the function. It takes the function object referenced by shout and creates a second name pointing to it, yell.
Example
def shout(text):
return text.upper()
print (shout("hello"))
yell = shout
print (yell("hello"))
Output
HELLO
HELLO
2. Function can be passed as arguments to other function
Because functions are objects we can pass them as arguments to other functions. Functions that can accept other functions as arguments are also called higher-order functions. In the example below, we have created a function greet which takes a function as an argument.
Example
def shout(text):
return text.upper()
def small(text):
return text.lower()
def greet(func):
# storing the function in a variable
greeting=func("Hello Students welcome to technical guptaji")
print(greeting)
func(shout)
func(small)
Output
HELLO STUDENTS WELCOME TO TECHNICAL GUPTAJI
hello students welcome to technical guptaji
3. Functions can return another function
Because functions are objects we can return a function from another function. In the below example, the create_adder function returns adder function.
Example
def create_adder(x):
def adder(y):
return (x+y)
return adder # return adder function
add_15 = create_adder(15)
print(add_15(10))
Output
25
No comments:
Post a Comment