Home
Aptitude
Categories


Home » Python

Python | Function as data type (Explain: First class, Closure)



Python function as data type: Here, we are going to 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.
Submitted by Pankaj Singh, on October 11, 2018

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) We can pass function as parameter to another function

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

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

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

Output

I am foo()

2) We can 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) We can 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

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.