Parameters of the Python function

Source: Internet
Author: User

Reference: Http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/ 001374738449338c8a122a7f2e047899fc162f4a7205ea3000

First, the default parameters

Use the default parameters to simplify the invocation of the function.

Note that you need to set default parameters:

(1) required parameter before, the default parameter is behind, otherwise the Python interpreter will error

(2) How to set 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.

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

In the case of n!=2, calling the function requires an explicit value of n, such as Power (5,3).

The default parameter must point to the immutable Object!!

 def  add_end (l=[]): L.append (  '  
 >>> Add_end () [ "  end   " "  >>> Add_end () [  " end  , "  end    '  >>> Add_end () [  '    end   ' ] 

Default parameters are inappropriate, as shown above, there will be an error!

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 [] .

Replace the above [] with none for this immutable object:

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

Two, variable parameters

Variable parameters that are, the number of arguments passed in the function is variable, can be any number, also can be 0.

For example, calculate a2 + b2 + C2 + ...

As the number of arguments is uncertain, the first thing we think of is the a,b,c ... To pass in a function as a list or tuple:

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

When calling a function, you need to assemble a list or a tuple first:

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

With variable parameters, calling a function simplifies:

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

This time the function is rewritten as:

def Calc (*numbers):    = 0    for in  numbers:        = sum + N * N     return sum

When you call a function, you can pass in any parameter, including 0 parameters.

If a list or a tuple already exists, you can change the list or tuple into a variable parameter pass-through function at the time of invocation, namely:

Python allows you to add a number to the list or tuple before * changing the elements of a list or tuple into mutable parameters.

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

Three, keyword parameters

The keyword parameter allows you to pass in 0 or any parameter with a parameter name, which is automatically assembled into a dict inside the function.

def person (name, age, * *kw)    :print'name:'  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', theother: {}

You can also pass in any number of keyword parameters:

>>> person ('Bob', city='Beijing') Name:bob Age:Other: {' City':'Beijing'}>>> person ('Adam', gender=,'M', job='Engineer') Name:adam Age: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, a dict can be assembled first.

>>> kw = {' City':'Beijing','Job':'Engineer'}>>> person ('Jack', 24, * *kw) Name:jack Age:Other: {' City':'Beijing','Job':'Engineer'}

Iv. Combination of parameters

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

def func (A, B, c=0, *args, * *kw)    :print'a ='  b ='c ='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': ' *}>>> func (*args, *= 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.

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.