(素材来源:Python Cookbook中文版,美David Beazley & Brian K. Jones著,陈舸 译)
一、接受任意数量参数的函数
以*打头的参数只能作为最后一个位置参数出现,以**打头的参数只能作为最后一个参数出现。
def anyargs(*args, **kwargs):
print(args) # tuple
print(kwargs) # dict
1. 位置参数
使用*表示
In [5]: def avg(first, *rest):
...: print(type(rest))
...: print(rest)
...: return (first + sum(rest))/(1 + len(rest))
...:
In [6]: avg(1, 2, 3, 4)
<class 'tuple'>
(2, 3, 4)
Out[6]: 2.5
In [7]:
2. 关键字参数 **
def make_element(name, value, **attrs):
print(type(attrs))
print(attrs)
keyvals = [' %s="%s"' % item for item in attrs.items()]
print('attrs.keys():', attrs.keys())
print('attrs.values():', attrs.values())
print('attrs.items():', attrs.items())
print('keyvals:', keyvals)
attr_str = ''.join(keyvals)
print('attr_str:', attr_str)
element = '<{name}{attrs}>{value}</{name}'.format(
name=name,
attrs=attr_str,
value=html.escape(value))
print('element:', element)
print('html.escape:', html.escape(value))
return element
# test
make_element('item', 'Albatross', size='large', quantity=6)
# =>out
<class 'dict'>
{'size': 'large', 'quantity': 6}
attrs.keys(): dict_keys(['size', 'quantity'])
attrs.values(): dict_values(['large', 6])
attrs.items(): dict_items([('size', 'large'), ('quantity', 6)])
keyvals: [' size="large"', ' quantity="6"']
attr_str: size="large" quantity="6"
element: <item size="large" quantity="6">Albatross</item
html.escape: Albatross
# test
make_element('p', '<spam>')
# =>out
<class 'dict'>
{}
attrs.keys(): dict_keys([])
attrs.values(): dict_values([])
attrs.items(): dict_items([])
keyvals: []
attr_str:
element: <p><spam></p
html.escape: <spam>
二、只接受关键字参数的函数
keyword-only参数,常常是一种提高代码可读性的好方法。
recv(1024, False)与recv(1024, block=False)对比。
放在以*打头的参数或者一个单独的*之后
1. 放在单独的*之后
def recv(maxsize, *, block):
'Receives a message'
print('maxsize:', maxsize)
print('block:', block)
pass
# test
recv(1024, True)
# ==> out
TypeError: recv() takes 1 positional argument but 2 were given
# test2
recv(1024, block=True)
# ==>out2
maxsize: 1024
block: True
2. 放在*打头的参数之后
def minimum(*values, clip=None):
print('type(values):', type(values))
print('values:', values)
print('type(clip):', type(clip))
print('clip:', clip)
m = min(values)
print('m:', m)
if clip is not None:
m = clip if clip > m else m
print('m:', m)
pass
# test1
minimum(1, 5, 2, -5, 10)
# ==>out1
type(values): <class 'tuple'>
values: (1, 5, 2, -5, 10)
type(clip): <class 'NoneType'>
clip: None
m: -5
# test2
minimum(1, 5, 2, -5, 10, clip=0)
# ==> out2
type(values): <class 'tuple'>
values: (1, 5, 2, -5, 10)
type(clip): <class 'int'>
clip: 0
m: -5
m: 0
三、显示帮助信息
在函数中写入''中,或使用注解。使用help(函数名)打印
def hello():
'hello func help test'
pass
# test
help(hello)
# ==> out
Help on function hello in module __main__:
hello()
hello func help test
# fun2
def add(x:int, y:int) -> int:
return x + y
# test2
help(add)
# ==>out2
Help on function add in module __main__:
add(x:int, y:int) -> int
四、元数据信息附加到函数参数上
函数的参数注解可以提示该函数应该如何使用。丰富文档内容。
注解会出现在文档中,使用help()可查看。
python解释器不会附加语法意义到参数注解上。既不是类型检查,也不会改变python的行为。一些第三方工具和框架可能会为注解加上语法含义。
任何类型的对象均可作为注解,通常只有类和字符串最有意义。
注解只保留在__annotations__属性中。
python没有类型声明,使用注解,可以带来更多提示。def s(int a, int b): => SyntaxError: invalid syntax
def add(x:int, y:int) -> int:
return x + y
# test1
help(add)
# ==>out1
Help on function add in module __main__:
add(x:int, y:int) -> int
# test2
add(1, 2)
#==> out2
3
# test3
add('1', '2')
# ==>out3
'12'
# test4
add.__annotations__
# ==>out4
{'x': int, 'y': int, 'return': int}
五、函数返回多个值——元组
元组通过逗号","来组成,不是圆括号(), 结果赋给多个变量,属于元组解包,赋给一个变量,该变量即为该元组
In [7]: a = (1, 2)
In [8]: a
Out[8]: (1, 2)
In [9]: b = 1, 2
In [10]: b
Out[10]: (1, 2)
In [11]: def myfun():
...: return 1, 2, 3
...:
In [12]: a, b, c = myfun()
In [13]: a
Out[13]: 1
In [14]: b
Out[14]: 2
In [15]: c
Out[15]: 3
In [16]:
六、带有默认参数的函数