1、可接受任意数量参数的函数
def avg(first, *rest):
return (first + sum(rest)) / (1 + len(rest))
# Sample use
avg(1, 2) # 1.5
avg(1, 2, 3, 4) # 2.5
def make_element(name, value, **attrs):
keyvals = [' %s="%s"' % item for item in attrs.items()]
attr_str = ''.join(keyvals)
print(attrs)
print(attrs.items())
element = '<{name}{attrs}>{value}{name}>'.format(
name=name,
attrs=attr_str,
value=value)
return element
# Example
make_element('item', 'Albatross', size='large', quantity=6)
输出
# {'size': 'large', 'quantity': 6}
# dict_items([('size', 'large'), ('quantity', 6)])
# '- Albatross
'
def anyargs(*args, **kwargs):
print(args) # A tuple
print(kwargs) # A dict
def a(x, *args, y):
pass
def b(x, *args, y, **kwargs):
pass
**参数只能出现在最后一个参数。有一点要注意的是,在 * 参数后面仍然可以定义其他参数。
2、只接受关键字参数的函数
def recv(maxsize, *, block):
'Receives a message'
pass
recv(1024, True) # TypeError
recv(1024, block=True) # Ok
def mininum(*values, clip=None):
m = min(values)
if clip is not None:
m = clip if clip > m else m
return m
minimum(1, 5, 2, -5, 10) # Returns -5
minimum(1, 5, 2, -5, 10, clip=0) # Returns 0
3、给函数参数增加元信息
def add(x:int, y:int) -> int:
return x + y
>>> help(add)
Help on function add in module __main__:
add(x: int, y: int) -> int
>>>
函数注解只存储在函数的 __annotations__ 属性中。例如:
>>> add.__annotations__
{'y': , 'return': , 'x': }
4、返回多个值的函数
>>> def myfun():
... return 1, 2, 3
...
>>> a, b, c = myfun()
>>> a
1
>>> b
2
>>> c
3
>>> a = (1, 2) # With parentheses
>>> a
(1, 2)
>>> b = 1, 2 # Without parentheses
>>> b
(1, 2)
>>>
>>> x = myfun()
>>> x
(1, 2, 3)
>>>
5、定义有默认参数的函数
def spam(a, b=42):
print(a, b)
spam(1) # Ok. a=1, b=42
spam(1, 2) # Ok. a=1, b=2
如果默认参数是一个可修改的容器比如一个列表、集合或者字典,可以使用 None作为默认值,就像下面这样:
# Using a list as a default value
def spam(a, b=None):
if b is None:
b = []
...
如果你并不想提供一个默认值,而是想仅仅测试下某个默认参数是不是有传递进来,可以像下面这样写:
_no_value = object()
def spam(a, b=_no_value):
if b is _no_value:
print('No b value supplied')
...
>>> spam(1)
No b value supplied
>>> spam(1, 2) # b = 2
>>> spam(1, None) # b = None
>>>
!!!!!! 默认参数的值仅仅在函数定义的时候赋值一次。试着运行下面这个例子:
>>> x = 42
>>> def spam(a, b=x):
... print(a, b)
...
>>> spam(1)
1 42
>>> x = 23 # Has no effect
>>> spam(1)
1 42
>>>
6、定义匿名或内联函数
>>> add = lambda x, y: x + y
>>> add(2,3)
5
>>> add('hello', 'world')
'helloworld'
>>>
lambda 表达式典型的使用场景是排序或数据 reduce 等:
>>> names = ['David Beazley', 'Brian Jones',
... 'Raymond Hettinger', 'Ned Batchelder']
>>> sorted(names, key=lambda name: name.split()[-1].lower())
['Ned Batchelder', 'David Beazley', 'Raymond Hettinger', 'Brian Jones']
>>>
7、匿名函数捕获变量值
>>> x = 10
>>> a = lambda y: x + y
>>> x = 20
>>> b = lambda y: x + y
>>>
>>> a(10)
30
>>> b(10)
30
>>>
这其中的奥妙在于 lambda 表达式中的 x 是一个自由变量,在运行时绑定值,而不是定义时就绑定,这跟函数的默认值参数定义是不同的。因此,在调用这个 lambda 表达式的时候, x 的值是执行时的值。例如:
>>> x = 15
>>> a(10)
25
>>> x = 3
>>> a(10)
13
>>>
如果你想让某个匿名函数在定义时就捕获到值,可以将那个参数值定义成默认参
数即可,就像下面这样:
>>> x = 10
>>> a = lambda y, x=x: x + y
>>> x = 20
>>> b = lambda y, x=x: x + y
>>> a(10)
20
>>> b(10)
30
>>>
>>> funcs = [lambda x: x+n for n in range(5)]
>>> for f in funcs:
... print(f(0))
...
4
4
4
4
4
>>>
>>> funcs = [lambda x, n=n: x+n for n in range(5)]
>>> for f in funcs:
... print(f(0))
...
0
1
2
3
4
>>>