DEV Community

Lody G Mtui
Lody G Mtui

Posted on • Edited on

First-Class Function in Python

Everything in Python is an Object (You heard it here first). Just kidding! Of course, at it's core everything in Python is an object.

Not all languages have this feature, but Python is one of them, together with JavaScript, Ruby etc.
This means, string, int, float, datatypes such as dictionary, list, tuple etc. are all objects.

Object is an entity with attributes and behavior. So, function in Python is treated as object. That's why you can call them as First-class function.

First-Class Function means that functions are treated as values - that you can assign a function into a variable, pass it around etc.

Properties of First-Class Function

  • you can assign them as variable.
  • you can pass them to other functions as arguments.
  • you can return them from other functions as values.
  • you can store them in data structures.

Lets dive into code examples for each property

1.Assigning function as variable.

def square(num):
    return num*num

# store the function in a variable
result = square
print(result2(3))
Enter fullscreen mode Exit fullscreen mode

2.Pass the function as a parameter to another function.

def morning():
    return "good morning"

def noon():
    return "good afternoon"

def greetings(function):
    greet = function()
    print(greet)

greetings(morning)
greetings(noon)
Enter fullscreen mode Exit fullscreen mode

3.Return function from other functions as values.

def outer_power(num1):
    def inner_power(num2):
        return num1 ** num2
    return inner_power

power = outer_power(4)
print(power(3))

Enter fullscreen mode Exit fullscreen mode

4.Store function in data structures

def plusOne(num):
    return num + 1

def plusTwo(num):
    return num + 2

def plusThree(num):
    return num + 3

list_function = [plusOne,plusTwo,plusThree]

for i in list_function:
    print(i)

print(plusOne)
print(plusTwo)
print(plusThree)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)