parameter types for Python

Source: Internet
Author: User
Tags pow

Ext.: http://blog.useasp.net/archive/2014/06/23/the-python-function-or-method-parameter-types.aspx

There are 4 types of parameters for functions in Python, namely:

    1. Position or keyword parameter (positional-or-keyword parameter)
    2. Positional-only parameters (positional-only parameter)
    3. Any number of positional parameters (var-positional parameter)
    4. Any number of keyword parameters (var-keyword parameter)

First: position or keyword parameters

This parameter is the default parameter type in Python, and after defining this parameter, you can pass the parameter as a positional parameter, or as a keyword parameter:

Code
123456789101112131415161718 ## 位置或者关键字参数## 这个是Python的默认参数类型## 示例:arg2提供了默认valuedef func(arg1, arg2="World!"):    print arg1, arg2## func可以通过位置参数形式调用func("Hello", "MitchellChu")## 也可以通过关键字参数的形式来调用funcfunc(arg1="Hello", arg2="World!")## 当然,混合的方式也是完全没有问题的func("Hello", arg2="World!")## 不过如果你不能将关键字参数优先于位置参数传递给函数(方法)## 这个调用方法是不能接受的,因为优先级不一样.后面会说func(arg1="Hello", "World!") ## ERROR

Second way: Only the form of positional parameters is applicable

This form can only be passed through positional parameters when parameters need to be passed to a function (method). This form is not available to Python developers for the time being. This form now exists only on many of the built-in functions of Python:

Code
1234567891011121314151617 ## Positional-only parameter has no syntax to define## 虽然无定义方法,但内建的很多函数都是仅接受位置参数的abs(-3) ## correctabs(a=3) ## wrong## Traceback (most recent call last):##   File "<stdin>", line 1, in <module>## TypeError: abs() takes no keyword argumentspow(x=2,y=3)## Traceback (most recent call last):##   File "<stdin>", line 1, in <module>## TypeError: pow() takes no keyword argumentspow(2,3)## 8

Third: Any number of positional parameters (with a single asterisk parameter)

Any number of positional parameters, when defined, require an asterisk prefix to indicate that, when passing parameters, you can add any number of arguments after the original parameter, which will be placed within the tuple to provide the function (method):

Code
123456789101112131415161718192021222324252627 ## var-positional parameter## 定义的时候,我们需要添加单个星号作为前缀def func(arg1, arg2, *args):    print arg1, arg2, args## 调用的时候,前面两个必须在前面## 前两个参数是位置或关键字参数的形式## 所以你可以使用这种参数的任一合法的传递方法func("hello", "Tuple, values is:", 2, 3, 3, 4)## Output:## hello Tuple, values is: (2, 3, 3, 4)## 多余的参数将自动被放入元组中提供给函数使用## 如果你需要传递元组给函数## 你需要在传递的过程中添加*号## 请看下面例子中的输出差异:func("hello", "Tuple, values is:", (2, 3, 3, 4))## Output:## hello Tuple, values is: ((2, 3, 3, 4),)func("hello", "Tuple, values is:", *(2, 3, 3, 4))## Output:## hello Tuple, values is: (2, 3, 3, 4)

Fourth type: Any number of keyword parameters (with two asterisk parameters)

Any number of keyword parameters at the time of definition, the parameter name needs to be preceded by two asterisks (* *) as a prefix, so defined parameters, when passing parameters, you can add any number of keyword parameters after the original parameter, the keyword parameter is used [ 参数名称=参数值 ] to pass the form:

Code
1234567891011121314151617181920212223242526272829303132333435 ## var-keywords parameter## 定义的时候,需要两个星号作为前缀def func(arg1, arg2, **kwargs):    print arg1, arg2, kwargsfunc("hello", "Dict, values is:", x=2, y=3, z=3)## Output:## 多余的参数将自动被放入字典中提供给函数使用## 如果你需要直接传递字典给函数## 你需要在传递的过程中添加**## 此时如果还有关键字参数应在字典前提供完成## 不能在字典后再提供## 请看下面例子中的输出差异:func("hello", "Dict., values is:", **{‘x‘:2, ‘y‘:3, ‘z‘:3})## hello Dict., values is: {‘y‘: 3, ‘x‘: 2, ‘z‘: 3}func("hello", "Dict., values is:", **{‘x‘:2, ‘y‘:3, ‘z‘:3,})## hello Dict., values is: {‘y‘: 3, ‘x‘: 2, ‘z‘: 3}func("hello", "Dict., values is:", {‘x‘:2, ‘y‘:3, ‘z‘:3})## Traceback (most recent call last):##   File "<stdin>", line 1, in <module>## TypeError: func() takes exactly 2 arguments (3 given)func("hello", "Dict., values is:", s=3, **{‘x‘:2, ‘y‘:3, ‘z‘:3,})## hello Dict., values is: {‘y‘: 3, ‘x‘: 2, ‘s‘: 3, ‘z‘: 3}## 提供了重复的参数func("hello", "Dict., values is:", y=3, **{‘x‘:2, ‘y‘:3, ‘z‘:3,})## Traceback (most recent call last):##   File "<stdin>", line 1, in <module>## TypeError: func() got multiple values for keyword argument ‘y‘

Summary: Only the second type of Python in four parameter forms does not provide a defined method, and the other three should be noted at the time of definition, which should be defined according to Python's parsing rules, where:

    1. The position or keyword parameter should be at the top, where no default value should precede the parameter with the default value
    2. Any number of positional parameters should be placed after all positions or keyword parameters
    3. Any number of keyword parameters should be placed after any number of positional parameters

Note: Any number of positional parameters and any number of keyword parameters can be defined only once in the definition.

Code
12345678910111213141516171819 ## 各种参数的混合使用例子## Author: MitchellChudef func(arg1, arg2=‘default‘, *args, **kwargs):    print "arg1=%s, arg2=%s, args=%s, kwargs=%s" % (arg1, arg2, args, kwargs)func(1) ## correctfunc(1,2) ## correctfunc(1,2,3,4) ## correctfunc(1,2,3,4,x=1,y=2) ## correctfunc(1,2,x=1) ## correctfunc(x=1) ## wrongfunc(arg1=1) ## correctfunc(1,x=1) ## correct## 可以将例子保存到parameter.py文件## 而后运行python /path/to/parameter.py

parameter types for Python

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.