Parameters of the function

Source: Internet
Author: User

Defining default parameters Keep in mind that the default parameter must point to the immutable object!

Default parameters

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

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‘)name: Sarahgender: Fage: 6city: Beijing

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

enroll(‘Bob‘, ‘M‘, 7)Note that it is not necessary to write parameter names if the parameters are initialized sequentially , such as this sentence
如果跳过中间某个有默认值得参数而直接对后面的数据初始化则需要写出变量名

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 str , None such an immutable object? 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.


可变参数

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

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

*numsIndicates that nums all elements of this list are passed in as mutable parameters. This writing is quite useful and very common



Parameters of the 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.