First Class functions in Python
- In Python when
functions treated like any other variable
then they are term as First-class functions - Properties of first class functions:
- Assign to a variable.
- Pass the function as a parameter to another function.
- Return a function from another function.
def one(msg):
print(msg)
one("Hello!")
two = one
two("Hello!")
Functions are objects
–> assigning function to a variable.
def shout(text):
return text.upper()
print(shout('Hello'))
# assigned to var
yell = shout
print(yell('Hello'))
Functions can be passed as arguments
to other functions
def shout(text):
return text.upper()
def whisper(text):
return text.lower()
def greet(func):
greeting = func("Hi, function ")
print(greeting)
# passed as arguments
greet(shout)
# HI, FUNCTION
greet(whisper)
# hi, function
Functions can return another function
def adder1(x):
print("adder1" + x )
return adder2
def adder2(y):
print("added2" + y)
adder = adder1('One')
print(adder)
adder('two')