Python parameters to understand

Python parameters to understand

  • Python is a function defined parameters mainly comprises four categories:
    • Required parameters
    • The default parameters
    • variable parameter
    • Keyword arguments

Required parameters

def power(x):
"""
x: 必选参数
"""
    return x ** 2

The default parameters

def power(x, n=2):
"""
n: 默认参数
"""
    return x ** n

variable parameter

I.e., the number of parameters is variable passed

def calc(*numbers):
"""
numbers: 可变参数
"""
    print numbers
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum

Called:
(. 1) Calc (. 1, 2,. 3)
(2) AA = [. 1, 2,. 3]
Calc (AA *)
parameter numbers received is a tuple: (1, 2, 3 )

Keyword arguments

Keyword parameter allows you pass 0 or any number of parameters including the parameter name, these keyword parameters are automatically assembled into a dict inside the function.

def person(name, age, **kw):
"""
kw: 关键字参数
"""
    print 'name:', name, 'age:', age, 'other:', kw

Called:
(. 1) Person ( 'Adam', 45, Gender = 'M', Job = 'Engineer')
(2) kW = { 'City': 'Beijing', 'Job': 'Engineer'}
Person ( 'Jack', 24, ** kw )

Parameter order

In-defined functions Python, you can use mandatory parameters, default parameters, variable parameters and keyword parameters, these four parameters can be used together, or only some, but please note that the order of the parameters must be defined: Required parameters, default parameters, variable parameters and keyword parameters.

Released seven original articles · won praise 0 · Views 16

Guess you like

Origin blog.csdn.net/WowClownGz/article/details/104815640