×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python Function as Data Type (First Class or Closure)

By IncludeHelp Last updated : December 08, 2024

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()

Comments and Discussions!

Load comments ↻





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