The First Class Objects in Python

1 minute read

In Python, functions are considered as first-class objects. This means that they can be treated like any other object in the language, such as strings, lists, or integers. Functions can be passed as arguments to other functions, returned as values from functions, and stored in variables.

Here is an example to illustrate this concept:

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    return a / b

def calculator(operation, a, b):
    return operation(a, b)

result1 = calculator(add, 10, 5)
print(result1) # Output: 15

result2 = calculator(subtract, 10, 5)
print(result2) # Output: 5

result3 = calculator(multiply, 10, 5)
print(result3) # Output: 50

result4 = calculator(divide, 10, 5)
print(result4) # Output: 2.0

In this example, we define four functions: 'add', 'subtract', 'multiply', and 'divide'. Then, we define a calculator function that takes three arguments: an operation (which is a function), and two numbers. Inside the 'calculator' function, we simply call the operation function with the two numbers as arguments and return the result.

We then use the 'calculator' function to perform various arithmetic operations by passing the appropriate operation function as an argument. For example, when we call 'calculator(add, 10, 5)', we are passing the add function as the operation argument, and the numbers 10 and 5 as the other two arguments. The 'calculator' function then calls the add function with the numbers 10 and 5, which returns the value 15. This value is then returned by the 'calculator' function and stored in the 'result1' variable.

Similarly, we use the 'subtract', 'multiply', and 'divide' functions to perform different arithmetic operations and store the results in different variables.

In summary, functions in Python are first-class objects, which means that they can be passed as arguments, returned as values, and stored in variables. This allows for a great deal of flexibility in programming and enables the creation of powerful, reusable code.

Updated: