Understanding the parameters of a function in Python

Source: Internet
Author: User
When defining a function, we determine the name and position of the parameter, and the interface definition of the function is completed. For the caller of the function, it is sufficient to know how to pass the correct arguments and what values the function will return, and the complex logic inside the function is encapsulated and the caller does not need to know.

Python's function definitions are very simple, but flexible but very large. In addition to the required parameters that are normally defined, you can also use default parameters, variable parameters, and keyword parameters so that the interfaces defined by the function can not only handle complex parameters, but also simplify the caller's code.
Default parameters

We still have a concrete example of how to define the default parameters for a function. Write a function to calculate the X2 first:

def power (x):  return x * x

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

>>> Power (5) 25>>> Power (15) 225

Now, what if we're going to calculate x3? You can define a Power3 function again, but if you want to calculate x4, X5 ... What to do? We cannot define an infinite number of functions.

As you might think, you can change power (x) to power (x, N) to calculate xn and say dry:

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

For this modified power function, you can calculate any n-times:

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

However, the old calling code failed because we added a parameter that prevented the old code from being called properly:

>>> Power (5) Traceback (most recent call last): File "
 
  
   
  ", line 1, in 
  
   
    
   typeerror:power () Takes exactly 2 arguments (1 given)
  
   
 
  

At this point, the default parameters will come in handy. Since we often calculate x2, we can completely 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

Thus, when we call Power (5), it is equivalent to calling power (5, 2):

>>> Power (5) 25>>> Power (5, 2) 25

For other cases of n > 2, it is necessary to explicitly pass in N, such as power (5, 3).

As you can see from the example above, the default parameters can simplify the invocation of a function. When setting default parameters, there are a few things to note:

The first is the required parameter before, the default parameter is behind, otherwise the Python interpreter will error (think about why the default parameters can not be placed in front of the required parameters);

The second is how to set the default parameters.

When the function has more than one parameter, the parameter with large change is put in front, and the parameters with small change are put back. Parameters with small variations can be used as default parameters.

What are the benefits of using default parameters? The biggest benefit is the ability to reduce the difficulty of calling a function.

For example, we write a function for first-year primary school students to register, need to pass in name and gender two parameters:

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

In this way, calling the Enroll () function only requires passing in two parameters:

>>> enroll (' Sarah ', ' F ') name:sarahgender:f

What if I continue to pass information about age, city, etc.? This will greatly increase the complexity of the calling function.

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 when registering, only two parameters must be provided:

>>> enroll (' Sarah ', ' F ') student:name:sarahgender:fage:6city:beijing

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

Enroll (' Bob ', ' m ', 7) Enroll (' Adam ', ' m ', city= ' Tianjin ')

Visible, the default parameters reduce the difficulty of function calls, and once more complex calls are required, you can pass more parameters to implement. The function only needs to define one, whether it is a simple call or a complex call.

When there are multiple default parameters, when called, the default parameters can be provided in order, such as calling enroll (' Bob ', ' M ', 7), which means that except for the Name,gender, the last 1 parameters are applied on the parameter age, and the city parameter is not provided, The default value is still used.

You can also provide some default parameters in order, not sequentially. When you do not provide partial default parameters in order, you need to write the parameter names. For example, call Enroll (' Adam ', ' M ', city= ' Tianjin '), meaning that the city parameter uses the passed in value, and the other default parameters continue to use the default value.

The default parameters are useful, but improper use will also fall out of the pit. The default parameter has a maximum pit, which is shown below:

First define a function, pass in a list, add an end and return:

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

When you call normally, the result looks 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 result is also right at the beginning:

>>> add_end () [' End ']

However, when you call Add_end () again, the result is incorrect:

>>> add_end () [' End ', ' End ']>>> add_end () [' End ', ' End ', ' end ']

Many beginners are puzzled, the default parameter is [], but the function seems to "remember" the last time the "END" after the list.

The reasons are explained as follows:

When the Python function is defined, the value of the default parameter L is computed, that is, [] because the default parameter, L, is also a variable, which points to the object [], each time the function is called, if the content of L is changed, the contents of the default parameter will change the next time the function definition is no longer [].

So, one thing to keep in mind when defining default parameters: The default parameter must point to the immutable object!

To modify the above example, we can use the none of the immutable object to achieve:

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

Now, no matter how many times it is called, there is no problem:

>>> add_end () [' End ']>>> add_end () [' End ']

Why design an immutable object such as Str and none? Since immutable objects are created, the data inside the object cannot be modified, which reduces the error caused by modifying the data. In addition, because the object is not changed, the simultaneous reading of objects in a multitasking environment does not require locking, while reading a little bit of a problem. When we are writing a program, if we can design a constant object, we try to design it as an immutable object.
Variable parameters

In the Python function, you can also define mutable parameters. As the name implies, the variable parameter is the number of parameters passed in is variable, can be one, 2 to any, or 0.

We take the math titled example, given a set of numbers a,b,c ..., please calculate a2 + b2 + C2 + ....

To define this function, we must determine the input parameters. As the number of arguments is uncertain, we first think that we can put a,b,c ... Passed in as a list or tuple, so that the function can be defined as follows:

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

But when called, a list or tuple needs to be assembled first:

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

If you take advantage of mutable parameters, the way you call a function can be simplified to this:

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

So, let's change the parameter of the function to a variable parameter:

Def calc (*numbers):  sum = 0 for  n in numbers:    sum = SUM + N * n  return sum

When you define a mutable parameter and define a list or tuple parameter, just precede the parameter with an * number. Inside the function, the parameter numbers receives a tuple, so the function code is completely unchanged. However, when you call the function, you can pass in any parameter, including 0 parameters:

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

What if you have a list or a tuple and you want to invoke a mutable parameter? You can do this:

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

This kind of writing is of course feasible, the problem is too cumbersome, so python allows you to precede the list or tuple with an * number, the list or tuple of the elements into a variable parameter to pass in:

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

This writing is quite useful and common.
Keyword parameters

Variable parameters allow you to pass in 0 or any of the parameters that are automatically assembled as a tuple when the function is called. The keyword parameter allows you to pass in 0 or any parameter with parameter names that are automatically assembled inside the function as a dict. Take a look at the example:

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

The function person accepts the keyword parameter kw, in addition to the required parameter name and age. When you call this function, you can pass in only the required parameters:

>>> person (' Michael ', "Name:michael age:30 other: {}

You can also pass in any number of keyword parameters:

>>> person (' Bob ', +, 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 keyword argument for? It can extend the functionality of the function. For example, in the person function, we are guaranteed to receive both the name and the age parameters, but we can receive them if the caller is willing to provide more arguments. Imagine you are doing a user registration function, in addition to the user name and age is required, the other is optional, using the keyword parameters to define this function can meet the requirements of registration.

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

>>> kw = {' City ': ' Beijing ', ' Jobs ': ' Engineer '}>>> person (' Jack ', ' city=kw[' city ', job=kw[' job ') Name:jack age:24 Other: {' City ': ' Beijing ', ' job ': ' Engineer '}

Of course, the above complex invocation can be simplified:

>>> kw = {' City ': ' Beijing ', ' job ': ' Engineer '}>>> person (' Jack ', ' **kw ') Name:jack age:24 other: {' C ity ': ' Beijing ', ' job ': ' Engineer '}

Parameter combinations

Defining functions in Python can be done with required parameters, default parameters, variable parameters, and keyword parameters, all of which can be used together, or only some of them, but note that the order of the parameters definition must be: required, default, variable, and keyword parameters. 4

For example, define a function that contains the above 4 parameters:

def func (A, B, c=0, *args, **kw):  print ' A = ', A, ' B = ', B, ' C = ', C, ' args = ', args, ' kw = ', kw

At the time of the function call, the Python interpreter automatically passes the corresponding parameters according to the parameter location and argument 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 = {}& gt;>> 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 the function:

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

So, for any function, it can be called by the form of a func (*args, **kw), regardless of how its arguments are defined.
Summary

Python's functions have a very flexible parameter pattern, which allows for simple invocation and very complex parameters to be passed.

The default parameter must be used immutable object, if it is a mutable object, run there will be a logic error!

Be aware of the syntax for defining mutable parameters and keyword parameters:

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

And how to pass in the syntax for variable and keyword arguments when calling a function:

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

Using *args and **kw is a Python idiom, but it can also be used with other parameter names, but it's best to use idioms.

  • 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.