Python Beginner Friendly丨Detailed Explanation of Parameter Passing Types

Summary:  This article clearly explains the different parameter passing types in Python and provides sample code to illustrate the usage of each type. It is very beneficial for beginners or readers who are not clear about Python parameter passing. The article provides enough information to understand and use function parameter passing in Python.

This article is shared from Huawei Cloud Community " Improving the Flexibility of Python Function Calls: Detailed Explanation of Parameter Passing Types ", author: frica01.

foreword

In Python programming, function parameters play a very important role. Function parameters allow us to pass data to a function and use those values ​​inside the function. Python provides a variety of parameter passing types, including positional parameters, keyword parameters, default parameters, variable number of positional parameters, and variable number of keyword parameters. These different ways of passing parameters make function calls more flexible and extensible. This article will talk about them in detail.

What is Python parameter passing

In Python, parameter passing refers to the process of passing data to a function during a function call. Passing parameters allows us to pass data to functions so that they can be manipulated and processed within the function.

In Python, the parameters used in the function definition are called formal parameters, also known as formal parameters. Formal parameters are placeholders used during function definition to receive values ​​passed to the function. Formal parameters are used as variables in the function body, and can be operated and processed in the function body.

Actual parameters, also known as arguments, are values ​​or variables that are passed to a function when it is called. Actual parameters are concrete values ​​or objects that are actually passed to the function. When we call a function, we need to provide the corresponding actual parameters for the formal parameters of the function, so that the function can perform the corresponding operation.

Here is a simple example:

def demo(name):
 print("Hello, " + name + "!")
demo("Frica")

In the above example, name is a formal parameter of the function demo.

When the function is called, the actual parameter Frica is passed to the function demo, which is assigned to the formal parameter name, and then the function body uses this value for printing.

To sum up, the formal parameter is a placeholder in the function definition for receiving the value passed to the function, and the actual parameter is the specific value or object that is actually passed to the function when the function is called. The correspondence between formal parameters and actual parameters enables the function to process and manipulate specific data.

Five types of parameter passing

The parameter passing types can be used alone or in combination. You can flexibly choose to use these parameter passing types in the function definition according to your needs.

The following are several common types of parameter passing in Python:

  1. Positional parameters : Positional parameters are the most common type of parameter, by providing parameter values ​​in the order in which they are defined;
  2. Keyword parameters : Keyword parameters allow the name of the parameter to be used to specify the value without having to supply the parameters in order;
  3. Default Parameters : Default parameters allow to provide a default value for one or more parameters of a function. If no parameter value is provided when the function is called, the function will use the default value;
  4. Variable number of positional arguments : A variable number of positional arguments allows to accept any number of positional arguments. In a function definition, use an asterisk (*) to specify a variable number of positional arguments, if no additional positional arguments are provided, args will be an empty tuple (());
  5. Variable number of keyword arguments : Variable number of keyword arguments allows to accept any number of keyword arguments. In a function definition, use double asterisks (**) to specify a variable number of keyword arguments, if no additional keyword arguments are provided, kwargs will be an empty dictionary ({}).

position parameter

Positional parameters : Positional parameters are the most common type of parameter. When defining a function, one or more positional parameters can be specified. When calling a function, you need to provide the corresponding values ​​in the order of the parameters. For example:

def demo(name, age):
 print("Hello", name, "!")
 print("You are", age, "years old.")
demo("Frica", 25)

In the example above, name and age are positional parameters, and "Frica" ​​and 25 are provided as parameter values, respectively, in that order.

Keyword parameter passing

Keyword arguments : Keyword arguments allow you to specify values ​​using the name of the argument without having to supply the arguments in order. Using keyword arguments can make code clearer and more readable. For example:

def demo(name, age):
 print("Hello", name, "!")
 print("You are", age, "years old.")
demo(age=25, name="Frica")

In the above example, the values ​​of the parameters are specified by using age=25 and name="Frica" ​​regardless of their order.

Default parameters

Default Parameters : Default parameters allow to provide a default value for one or more parameters of a function.

If no parameter value is provided when the function is called, the function will use the default value. Default parameters are usually specified in the function definition and must be placed after the positional parameters (otherwise there will be a SyntaxError exception). For example:

def demo(name, age=18):
 print("Hello", name, "!")
 print("You are", age, "years old.")
demo("Frica") # 使用默认值18
demo("Frica01", 25) # 覆盖默认值

In the above example, the age parameter has a default value of 18. If no parameter value is provided for age, the function will use a default value.

variable number of positional arguments

Generally, we will use *args, of course, other variables can also be used (the key here is *, not args.

Variable number of positional arguments : Variable number of positional arguments allows to accept any number of positional arguments. A variable number of arguments can be used in cases where it may be uncertain how many arguments a function will accept. In a function definition, an asterisk (*) can be used to specify a variable number of positional parameters. For example:

def print_info(*args):
 print(type(args))# 输出: <class 'tuple'>
    total = sum(num for num in args)
 return total
result = print_info(1, 2, 3, 4, 5)

print(result) # output: 15

In the above example, the print_info function takes any number of positional arguments and adds them together.

Variable number of keyword arguments

Generally, we will use **kwargs, of course, other variables can also be used (the key here is **, not kwargs.

Variable number of keyword arguments passing : Variable number of keyword arguments allows to accept any number of keyword arguments. In function definitions, double asterisks (**) can be used to specify a variable number of keyword arguments. For example:

def print_info(**kwargs):
 print(type(kwargs)) # 输出: <class 'dict'>
 for key, value in kwargs.items():
 print(key, ":", value)
print_info(name="Frica", age=25, city="GuangZhou")

In the example above, the demo function takes any number of keyword arguments and prints them.

Combination of multiple parameter passing types

def print_info(name, *args, age=18, **kwargs):
 print("Name:", name)
 print("Age:", age)
 print("Additional arguments:")
 for arg in args:
 print("-", arg)
 print("Keyword arguments:")
 for key, value in kwargs.items():
 print("-", key, ":", value)
print_info("Frica", "arg1", "arg2", age=25, city="GuangZhou", country="China")

In the above example, the function print_info accepts the following parameters:

  • name is a positional parameter and a value must be provided.
  • *args is a variable number of positional arguments that can accept any number of additional arguments.
  • age is a keyword argument with a default value.
  • **kwargs is a variable number of keyword arguments that can accept any number of keyword arguments.

By calling the print_info function and providing corresponding parameters, these parameter types can be combined and used flexibly. Inside the function body, these parameters can be accessed and manipulated as needed.

When the print_info function is called, the output is as follows:

Name: Frica
Age: 25
Additional arguments:
- arg1
- arg2
Keyword arguments:
- city : GuangZhou
- country : China

This example shows a combination of various argument types, including positional arguments, variable number of positional arguments, keyword arguments with default values, and variable number of keyword arguments. Readers can flexibly use these parameter types in functions according to actual development needs.

Function parameter type annotation

Here we take positional parameters as an example,

def demo(name: str, age: int) -> str:
 return "Hello, " + name + "! You are " + str(age) + " years old."
print(demo("Frica", 25))# 输出: Hello, Frica! You are 25 years old.

In this example, the type of the parameter name is annotated as a string type str, the type of the parameter age is annotated as an integer type int, and the type of the return value is annotated as a string type str. Parameter type annotations can provide type hints to help developers better understand the expected types of parameters and return values ​​of functions.

Of course, this is only equivalent to a comment, even if other types of data are passed in, no error will be reported! ! !

Summarize

This article explains the different types and ways of passing function parameters in Python.

  • Positional parameters are the most common type of parameter, providing parameter values ​​in the order in which they are defined.
  • Keyword arguments allow the use of parameter names to specify values, improving code readability.
  • Default parameters provide default values ​​for one or more parameters of a function, and optionally provide parameter values ​​when the function is called.
  • Variable number of positional parameters and variable number of keyword parameters allows to accept any number of positional parameters and keyword parameters, providing the convenience of dealing with indeterminate number of parameters.

In the function definition, we can flexibly choose to use these parameter transfer types according to the needs to meet the needs of development. By choosing the type of parameter transfer reasonably, the function call can be made more convenient and readable, and the scalability of the code can be improved.

 

Click to follow and learn about Huawei Cloud's fresh technologies for the first time~

{{o.name}}
{{m.name}}

Guess you like

Origin my.oschina.net/u/4526289/blog/10083151