python - arguments to a function

Python's function definition is very simple, but it is very flexible. In addition to the required parameters that are normally defined, default parameters, variable parameters and keyword parameters can also be used, so that the interface defined by the function can not only handle complex parameters, but also simplify the caller's code.

positional parameters

Positional parameters are very simple, that is, they are assigned in sequence according to the position.

default parameters

One is that the mandatory parameters come first, and the default parameters come after, otherwise the Python interpreter will report an error (think about why the default parameters cannot be placed in front of the mandatory parameters);

The second is how to set the default parameters.

When the function has multiple parameters, put the parameters with large changes in the front, and put the parameters with small changes in the back. Parameters with small changes can be used as default parameters.

What are the benefits of using default parameters? The biggest advantage is that it can reduce the difficulty of calling functions.

Why use immutable objects

Why design immutable objects such as str and None? Because once an immutable object is created, the data inside the object cannot be modified, which reduces errors caused by modifying data. In addition, since the object does not change, reading the object at the same time in a multitasking environment does not need to be locked, and there is no problem with reading at the same time. When we write a program, if we can design an immutable object, we should try to design it as an immutable object.

variable parameter

In Python functions, it is also possible to define variadic parameters. As the name implies, a variable parameter means that the number of parameters passed in is variable, which can be 1, 2 to any number, or 0.
*numsIt's so much more convenient

parameter combination

To define a function in Python, you can use required parameters, default parameters, variable parameters, keyword parameters and named keyword parameters, all of which can be used in combination. Note, however, that the order of parameter definitions must be: required parameters, default parameters, variadic parameters, named keyword parameters, and keyword parameters.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325503818&siteId=291194637