Understand the function parameters in Python.

Source: Internet
Author: User

Understand the function parameters in Python.

When defining a function, we can determine the parameter name and position, and define the function interface. For a function caller, you only need to know how to pass the correct parameters and what values the function will return. The complex logic inside the function is encapsulated, And the caller does not need to know.

Python functions are easy to define, but flexible. In addition to the required parameters, you can also use default parameters, variable parameters, and keyword parameters, so that the interface defined by the function can not only process complex parameters, it also simplifies the caller's code.
Default parameters

The following example shows how to define the default parameters of a function. First, write a function to calculate x2:

def power(x):  return x * x

When we call the power function, we must pass in one and only one parameter x:

>>> power(5)25>>> power(15)225

What if we want to calculate x3? You can define another power3 function, but if you want to calculate x4, x5 ...... What should I do? We cannot define an infinite number of functions.

You may have thought about how to change power (x) to power (x, n) to calculate xn:

def power(x, n):  s = 1  while n > 0:    n = n - 1    s = s * x  return s

The modified power function can calculate any n power:

>>> power(5, 2)25>>> power(5, 3)125

However, the old call Code fails because a parameter is added, which makes the old code unable to call normally:

>>> power(5)Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: power() takes exactly 2 arguments (1 given)

In this case, the default parameters are used. Since we often calculate x2, we can set the default value of the second parameter n to 2:

def power(x, n=2):  s = 1  while n > 0:    n = n - 1    s = s * x  return s

In this way, when we call power (5), it is equivalent to calling power (5, 2 ):

>>> power(5)25>>> power(5, 2)25

For n> 2, n, such as power (5, 3), must be explicitly input ).

As shown in the preceding example, the default parameters can simplify function calls. Note the following when setting default parameters:

First, the required parameter is in the front, and the default parameter is in the back; otherwise, the Python interpreter reports an error (think about why the default parameter cannot be placed before the required parameter );

Second, set the default parameters.

When a function has multiple parameters, place the parameters with major changes first and those with minor changes later. A parameter with a small change can be used as the default parameter.

What are the advantages of using default parameters? The biggest benefit is that it can reduce the difficulty of calling a function.

For example, if we write a function registered by a first-year elementary school student, we need to input two parameters: name and gender:

def enroll(name, gender):  print 'name:', name  print 'gender:', gender

In this way, to call the enroll () function, you only need to input two parameters:

>>> enroll('Sarah', 'F')name: Sarahgender: F

What if I want to continue to input age, city, and other information? This will greatly increase the complexity of calling functions.

We can set the age and City as the default parameters:

def enroll(name, gender, age=6, city='Beijing'):  print 'name:', name  print 'gender:', gender  print 'age:', age  print 'city:', city

In this way, most students do not need to provide age and city at registration, but only two required parameters are provided:

>>> enroll('Sarah', 'F')Student:name: Sarahgender: Fage: 6city: Beijing

Only students that do not match the default parameters need to provide additional information:

enroll('Bob', 'M', 7)enroll('Adam', 'M', city='Tianjin')

It can be seen that the default parameters reduce the difficulty of function calling. When more complex calls are required, more parameters can be passed for implementation. For simple or complex calls, you only need to define one function.

When there are multiple default parameters, you can provide the default parameters in sequence when calling, such as calling enroll ('bob', 'M', 7), meaning that, except for name, except the gender parameters, the last parameter is applied to the parameter age. Because the city parameter is not provided, the default value is still used.

You can also choose not to provide some default parameters in order. When some default parameters are not provided in order, you need to write the parameter name. For example, if you call enroll ('Adam ', 'M', city = 'tianjin'), the city parameter uses the value passed in. Other Default parameters continue to use the default value.

Default parameters are useful, but improper use may also result in pitfalls. The default parameter has the largest pitfall, as shown below:

Define a function, input a list, add an END, and return the result:

def add_end(L=[]):  L.append('END')  return L

When you call it normally, the results seem to be good:

>>> add_end([1, 2, 3])[1, 2, 3, 'END']>>> add_end(['x', 'y', 'z'])['x', 'y', 'z', 'END']

When you use the default parameter call, the initial result is also correct:

>>> add_end()['END']

However, when add_end () is called again, the result is incorrect:

>>> add_end()['END', 'END']>>> add_end()['END', 'END', 'END']

Many beginners are confused. The default parameter is [], but the function seems to "remember" The list after 'end' is added last time.

The reasons are as follows:

When defining a Python function, the value of the default parameter L is calculated, that is, []. Because the default parameter L is also a variable, it points to the object [], every time you call this function, if the content of L is changed, the content of the default parameter will change next time. It is no longer the [] of the function definition.

Therefore, to define default parameters, remember that the default parameters must point to unchanged objects!

To modify the example above, we can use the unchanged object None to implement:

def add_end(L=None):  if L is None:    L = []  L.append('END')  return L

Now, no matter how many calls, there will be no problem:

>>> add_end()['END']>>> add_end()['END']

Why do we need to design immutable objects such as str and None? Because once a constant object is created, the data in the object cannot be modified, which reduces errors caused by data modification. In addition, because the object remains unchanged, there is no need to lock the object to be read at the same time in the multi-task environment. When writing a program, if we can design a constant object, we should try to design it as a constant object.
Variable parameters

Variable parameters can also be defined in Python functions. As the name suggests, a variable parameter means that the number of input parameters is variable, which can be 1, 2 to any, or 0.

Let's use a mathematical example to give a group of numbers a, B, c ......, Calculate a2 + b2 + c2 + .......

To define this function, we must determine the input parameters. Because the number of parameters is unknown, We can first consider a, B, c ...... As a list or tuple, the function can be defined as follows:

def calc(numbers):  sum = 0  for n in numbers:    sum = sum + n * n  return sum

However, you need to first assemble a list or tuple:

>>> calc([1, 2, 3])14>>> calc((1, 3, 5, 7))84

If variable parameters are used, the method of calling a function can be simplified as follows:

>>> calc(1, 2, 3)14>>> calc(1, 3, 5, 7)84

Therefore, we change the function parameters to variable parameters:

def calc(*numbers):  sum = 0  for n in numbers:    sum = sum + n * n  return sum

Compared with defining the list or tuple parameter, Variable Parameter definition only adds a * sign before the parameter. In a function, the numbers parameter receives a tuple. Therefore, the function code remains unchanged. However, when calling this function, you can input any parameter, including 0 parameters:

>>> calc(1, 2)5>>> calc()0

If a list or tuple already exists, what should I do if I want to call a variable parameter? You can do this:

>>> nums = [1, 2, 3]>>> calc(nums[0], nums[1], nums[2])14

This method is feasible, and the problem is too cumbersome. Therefore, Python allows you to add a * sign before list or tuple to convert the list or tuple elements into variable parameters and pass them in:

>>> nums = [1, 2, 3]>>> calc(*nums)14

This method is quite useful and common.
Keyword Parameter

Variable parameters allow you to input 0 or any parameter. These variable parameters are automatically assembled into a tuple during function calling. Keyword parameters allow you to input 0 or any parameters with parameter names. These keyword parameters are automatically assembled into a dict in the function. See the example:

def person(name, age, **kw):  print 'name:', name, 'age:', age, 'other:', kw

In addition to the required parameter name and age, the person function also accepts the keyword kw. When calling this function, you can only input the required parameters:

>>> person('Michael', 30)name: Michael age: 30 other: {}

You can also input any number of keyword parameters:

>>> person('Bob', 35, city='Beijing')name: Bob age: 35 other: {'city': 'Beijing'}>>> person('Adam', 45, gender='M', job='Engineer')name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}

What is the use of keyword parameters? It can expand functions of functions. For example, in the person function, we ensure that the two parameters name and age can be received. However, if the caller is willing to provide more parameters, we can also receive them. Imagine that you are working on a user registration function. Except that the user name and age are mandatory, other functions are optional. Using Keyword parameters to define this function can meet the registration requirements.

Similar to variable parameters, You can assemble a dict and then convert the dict into a keyword parameter:

>>> kw = {'city': 'Beijing', 'job': 'Engineer'}>>> person('Jack', 24, city=kw['city'], job=kw['job'])name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}

Of course, the above complex calls can be simplified:

>>> kw = {'city': 'Beijing', 'job': 'Engineer'}>>> person('Jack', 24, **kw)name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}

Parameter combination

Define functions in Python. You can use required parameters, default parameters, variable parameters, and keyword parameters. These four parameters can be used together or only use some of them, the order of parameter definitions must be: mandatory parameter, default parameter, variable parameter, and keyword parameter.

For example, defining a function includes the preceding four parameters:

def func(a, b, c=0, *args, **kw):  print 'a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw

When a function is called, the Python interpreter automatically transmits the corresponding parameters according to the parameter location and parameter name.

>>> func(1, 2)a = 1 b = 2 c = 0 args = () kw = {}>>> func(1, 2, c=3)a = 1 b = 2 c = 3 args = () kw = {}>>> func(1, 2, 3, 'a', 'b')a = 1 b = 2 c = 3 args = ('a', 'b') kw = {}>>> func(1, 2, 3, 'a', 'b', x=99)a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99}

The most amazing thing is that through a tuple and dict, you can also call this function:

>>> args = (1, 2, 3, 4)>>> kw = {'x': 99}>>> func(*args, **kw)a = 1 b = 2 c = 3 args = (4,) kw = {'x': 99}

Therefore, any function can be called in a way similar to func (* args, * kw), regardless of how its parameters are defined.
Summary

Python functions have a flexible parameter form, which can be used for simple calls and very complex parameters.

The default parameter must use an immutable object. If it is a mutable object, a logic error occurs during running!

Pay attention to the syntax for defining variable parameters and keyword parameters:

  • * Args is a variable parameter, and args receives a tuple;
  • ** Kw is a keyword parameter, and kw receives a dict.

And how to pass in the Variable Parameter and keyword parameter syntax when calling the function:

  • Variable parameters can be passed in directly: func (1, 2, 3), list or tuple can be assembled first, and then passed in through * args: func (* (1, 2, 3 ));
  • Keyword parameters can be passed in directly: func (a = 1, B = 2), dict can be assembled first, and then passed in through ** kw: func (** {'A ': 1, 'B': 2 }).

The use of * args and ** kw is a habit of writing in Python. Of course, you can also use other parameter names, but it is best to use them.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.