Parameters of the Python function

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 a power function, we must pass in the only one parameter x :

>>> Power (5)25>>> Power (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.

You may have thought of it, you can power(x) change it power(x, n) , use it to calculate xn, and say dry.

def Power (x,n):     = 1     while n > 0:        = n-1        = S *x    return  s  Print power (5,2)print power (5,3)

For this modified power function, you can calculate the arbitrary n-th-square:

>>> 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 "<stdin>", line 1, in <module>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

n > 2in other cases, it is necessary to explicitly pass N, for example 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, suppose you want to draw a circle on the screen, because the circle only needs to determine the center coordinate (x, y) and radius r , so let's say we can call the function like this:

>>> x, y = 0, 0>>> r = 20>>> draw_circle(x, y, r)

The drawing is like this:

But what if you want to draw a red circle? Fortunately, the function is written by draw_circle a senior Python developer, which provides default parameters in addition to the X,Y,R 3 required parameters linecolor=0x000000,fillcolor=0xffffff,penwidth= 1, if we change the default parameters, we can not only draw a red circle, but also control the line thickness and fill color of the circle:

>>> draw_circle(0, 0, 20, linecolor=0xff0000)>>> draw_circle(0, 0, 20, linecolor=0xff0000, penwidth=5)>>> draw_circle(0, 0, 20, linecolor=0xff0000, fillcolor=0xffff00, penwidth=5)

The results are as follows:

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 the call draw_circle(0, 0, 20, 0xff0000, 0xffff00) , meaning that, except 0 , 0 20 These 3 required parameters, the last two parameters are applied to the parameters linecolor and fillcolor above, the penwidth parameters are 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, the call draw_circle(0, 0, 20, fillcolor=0x00ff00) , meaning that the fillcolor parameter is passed in the value 0x00ff00 , 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 one and END 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 called again add_end() , the result is incorrect:

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

Many beginners are puzzled, the default argument is [] , but the function seems to "remember" the last time the list was added ‘END‘ .

The reasons are explained as follows:

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

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

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

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 a * 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 add a number in front of a list or a tuple * , the elements of a list or a tuple into a mutable 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

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

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

You can also pass in 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 keyword argument for? It can extend the functionality of the function. For example, in a person function, we are guaranteed to receive name and both age parameters, but if the caller is willing to provide more arguments, we can receive them. 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‘, ‘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 invocation can be simplified:

>>> kw = {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘}>>> person(‘Jack‘, 24, **kw)name: Jack age: 24 other: {‘city‘: ‘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 = {}>>> 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 in a similar func(*args, **kw) way, 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:

*argsis a variable parameter, and args receives a tuple;

**kwis a keyword parameter, kw receives a dict.

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

Variable parameters can be directly passed func(1, 2, 3) in:, you can first assemble a list or a tuple, and then pass in *args : func(*(1, 2, 3)) ;

Keyword parameters can be directly passed in: func(a=1, b=2) , you can first assemble dict, and then pass in **kw : func(**{‘a‘: 1, ‘b‘: 2}) .

It *args is customary to use and **kw be python, but it is also possible to use other parameter names, but it's best to get used to idioms.

Now there is a problem: If the default parameters are used together with the mutable parameters, can you not pass in the default parameters? That is, the default parameter uses the default value

Python parameters are required parameters of the default parameter variable parameter keyword parameter, the variable parameter is understood to facilitate the transfer of tuple, key parameters convenient transfer dict

Parameters of the Python function

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.