In Python, functions are first-class objects, which means they can be treated like any other object, such as an integer, string, or list. This means that you can assign a function to a variable, pass a function as an argument to another function, or even return a function from a function.
Here's an example of assigning a function to a variable:
def greeting(name): print('Hello, {}!'.format(name))greet = greetinggreet('Alice') # prints "Hello, Alice!" |
In this example, the greeting function is defined to print a greeting message to the console. The greet variable is then assigned to the greeting function, so that calling greet is equivalent to calling greeting.
Here's an example of passing a function as an argument to another function:
def apply_operation(x, operation): return operation(x)def double(x): return x * 2result = apply_operation(5, double) # result = 10 |
In this example, the apply_operation function takes two arguments: a number x and an operation function. The apply_operation function then calls the operation function with the x argument and returns the result. The double function is defined to double its argument, and is passed as the operation function to apply_operation along with the value 5.
Finally, here's an example of returning a function from a function:
def make_adder(n): def adder(x): return x + n return adderadd5 = make_adder(5)result = add5(3) # result = 8 |
In this example, the make_adder function takes a number n and returns a new function adder that adds n to its argument. The add5 variable is assigned to the function returned by make_adder with the argument 5. The add5 function can then be called with an argument 3, which returns the result 8.
In summary, treating functions as objects allows you to write more flexible and reusable code by passing functions as arguments, returning functions from functions, and assigning functions to variables.