Python Function as Data Type | Python First Class or Closure

Python function as a data type: In this tutorial, we will learn the concept of the function, where we can use it as the data type, also we will learn about the first class and the closure. By Pankaj Singh Last updated : December 30, 2023

Python First Class

In Python, a function is a type. That's why Python function is known as "First class". So,

  1. We can pass function as parameter to another function
  2. We can return function as return value
  3. We can define a new function inside another function (this feature is known as "Closure")

1. Pass function as parameter to another function

Python allows passing a function as a parameter to another function.

Example to pass function as parameter to another function

# defining a function
def foo():
    print("I am foo()")

# defining another function which is receiving
# function as parameter
def koo(x):
    x()

# calling second function and passing first function
# as parameter
koo(foo)

Output

I am foo()

2. Return function as return value

Python allows returning a function as its return value.

Example to return function as return value

# defining first function
def foo():
    print("I am foo()")

# defining second function which is returning
# first function as return value
def koo():
    return foo

# calling second function and recieving
# reference of first function
x = koo()
x()

Output

I am foo()

3. Define a new function inside another function

Python allows defining a new function inside a function.

Example to define a new function inside another function

# Function inside function
# definition of parent function
def foo():
    # definition of child function
    def koo():
        print("I am koo()")

    print("I am foo()")
    koo()

foo()

# koo() cannot be called here, because
# it's scope is limited to foo() only
# koo()  # it will not work

Output

I am foo()
I am koo()

Python Tutorial

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.