- Python Functions – Complete Tutorial
- Table of contents
- Types of functions
- How to Pass a Method as an Argument in Python?
- Note:
- Example: A Class Method Passed as an Argument
- Example: Higher Order Functions Passed as an Argument
- Example: Wrapper Function Passed as an Argument
- Example: Lambda Passed as an argument to map()
- Conclusion
Python Functions – Complete Tutorial
In any programming language, the function is a reusable block of code that allows us to implement repetitive tasks in the code without code duplication. Functions allow you to write clean, organized, and manageable code. This Python functions tutorial covers Python functions, their syntax, arguments, return statements, Python function annotations, and many more.
Table of contents
Types of functions
In Python, functions are defined to perform a specific task. Several types of Functions can be used in Python, each with its capabilities. The first function type is the built-in function. For example, the ‘print’ function displays text on the screen, or the ‘input’ function allows the user to enter data into the program.
Functions can also be defined to reuse code, known as user-defined functions. User-defined functions can take arguments, which are values passed into the function to change its behavior. For example, a user-defined function could be written to calculate the area of a rectangle, and the width and height would be passed in as arguments.
Finally, there are also anonymous functions, which are Python functions that do not have a name. These functions are commonly used when they only need to be used once or are too complicated to be written as a single line of code.
By understanding each type of function’s capabilities, programmers can write more efficiently and easier-to-understand programs.
- Math operations
- Type conversion
- Managing iterators
- Managing composite data types
- Working with classes
- Manage variables, references, and scope
Python developers declare any functions in their code are called user-defined functions, which are the primary focus of this article.
How to Pass a Method as an Argument in Python?
In this article, we will learn how to pass a method as an argument in Python. We will discuss the different methodology of passing methods and functions as arguments using custom codes as well.
In Python, everything such as objects, variables, etc. is treated as an object. Therefore, functions/methods, are too treated as objects. In this article, we will stick to methods. A method can take multiple arguments, like objects, variables(of same or different data types), and even other methods because python methods are first-class objects. Methods are callable objects so you can pass them, store them, and can do whatever you want to. __call__ method is associated with every method and gets called automatically when you invoke the method with or without arguments. You can think about a method (or function) as a variable whose value is the actual callable code object. A user-defined method or a built-in method both can be passed as an argument to another method in python.
Note:
In this article, we will use methods in the following examples, but note that everything below applies identically to functions (except without the self parameter). Functions and methods both are utility blocks of code, but when a utility function is defined inside a class, it is known as a method. Don’t get confused between methods and functions. All functions in Python can be passed as an argument to another function.
Example: A Class Method Passed as an Argument
Methods are passed as arguments just like a variable. In this example, we define a class and its objects. We create an object to call the class methods. Now, to call a passed method or function, you just use the name it’s bound to in the same way you would use the method’s (or function’s) regular name.
Note: If you want to pass a method of a class as an argument but don’t yet have the object on which you are going to call it, you can simply pass the object once you have it as the first argument (i.e. the «self» argument).
class my_class: def method1(self): return "Hello World" def method2(self, methodToRun): result = methodToRun() return result obj = my_class() #method1 is passed as an argument print(obj.method2(obj.method1))
Example: Higher Order Functions Passed as an Argument
Just like class methods are called using class objects and are passed as arguments, a general user-defined function can also be passed as an argument to another function because functions are objects. Functions that can accept another function as arguments are called higher-order functions. In the example below, a function func1 is created which takes a function as an argument.
def func2(text): return text.upper() def func3(text): return text.lower() def func1(func): # storing the function in a variable res = func("Hello World") print(res) #funtion calls func1(func2) func1(func3)
Example: Wrapper Function Passed as an Argument
In Python, Wrapper functions or decorators wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it. In Decorators, functions are passed as the argument to another function and then they are called inside the wrapper function.
The below example defines a simple decorator hello_decorator. inner1 is a Wrapper function in which the argument is called. The inner function can access the outer local functions like in this case func(). func() is called inside the wrapper function.
#decorator def hello_decorator(func): #Wrapper function def inner1(): print("Hello, this is before function execution") func() print("This is after function execution") return inner1 # defining a function, to be called inside wrapper def function_to_be_used(): print("This is inside the function !!") # pass 'function_to_be_used' inside the decorator to control its behavior function_to_be_used = hello_decorator(function_to_be_used) # calling the function function_to_be_used()
Hello, this is before function execution
This is inside the function !!
This is after function execution
Example: Lambda Passed as an argument to map()
The most important example of passing methods as arguments is lambda. You often use map() and lambda together to perform various list operations and many more in python. In python, a lambda expression is a special syntax for creating an anonymous function. When you evaluate a lambda expression the object you get back is called a lambda function. Lambda functions are just like regular Python functions, with a few caveats.
Python implements the map() function where the first parameter is a function and the second is iterable. In this example, the function call passes the function sqr(x) as a function argument using the map method. Another way to use the map() method is to pass lambda as an argument with iterable.
def sqr(x): return x ** 2 list1 = [1, 3, 5, 7, 9] list(map(sqr, list1)) #use lambda print(list(map((lambda x: x**2), list1)))
Conclusion
In this article, we learned to pass a method and function as arguments to another function. Every example has its own methodology. Lambda expression as an argument to map() method is the best example to understand this article because you have used them together multiple times. Try passing different functions as arguments to other functions and observe the behavior.