1、可接受任意數(shù)量參數(shù)的函數(shù)
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)])
# '<item size="large" quantity="6">Albatross</item>'
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
**參數(shù)只能出現(xiàn)在最后一個參數(shù)。有一點(diǎn)要注意的是抓歼,在 * 參數(shù)后面仍然可以定義其他參數(shù)。
2拢锹、只接受關(guān)鍵字參數(shù)的函數(shù)
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谣妻、給函數(shù)參數(shù)增加元信息
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
>>>
函數(shù)注解只存儲在函數(shù)的 __annotations__ 屬性中。例如:
>>> add.__annotations__
{'y': <class 'int'>, 'return': <class 'int'>, 'x': <class 'int'>}
4卒稳、返回多個值的函數(shù)
>>> 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蹋半、定義有默認(rèn)參數(shù)的函數(shù)
def spam(a, b=42):
print(a, b)
spam(1) # Ok. a=1, b=42
spam(1, 2) # Ok. a=1, b=2
如果默認(rèn)參數(shù)是一個可修改的容器比如一個列表、集合或者字典充坑,可以使用 None作為默認(rèn)值减江,就像下面這樣:
# Using a list as a default value
def spam(a, b=None):
if b is None:
b = []
...
如果你并不想提供一個默認(rèn)值,而是想僅僅測試下某個默認(rèn)參數(shù)是不是有傳遞進(jìn)來捻爷,可以像下面這樣寫:
_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
>>>
!!!!!! 默認(rèn)參數(shù)的值僅僅在函數(shù)定義的時候賦值一次辈灼。試著運(yùn)行下面這個例子:
>>> x = 42
>>> def spam(a, b=x):
... print(a, b)
...
>>> spam(1)
1 42
>>> x = 23 # Has no effect
>>> spam(1)
1 42
>>>
6、定義匿名或內(nèi)聯(lián)函數(shù)
>>> add = lambda x, y: x + y
>>> add(2,3)
5
>>> add('hello', 'world')
'helloworld'
>>>
lambda 表達(dá)式典型的使用場景是排序或數(shù)據(jù) 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也榄、匿名函數(shù)捕獲變量值
>>> x = 10
>>> a = lambda y: x + y
>>> x = 20
>>> b = lambda y: x + y
>>>
>>> a(10)
30
>>> b(10)
30
>>>
這其中的奧妙在于 lambda 表達(dá)式中的 x 是一個自由變量巡莹,在運(yùn)行時綁定值,而不是定義時就綁定,這跟函數(shù)的默認(rèn)值參數(shù)定義是不同的降宅。因此骂远,在調(diào)用這個 lambda 表達(dá)式的時候, x 的值是執(zhí)行時的值腰根。例如:
>>> x = 15
>>> a(10)
25
>>> x = 3
>>> a(10)
13
>>>
如果你想讓某個匿名函數(shù)在定義時就捕獲到值激才,可以將那個參數(shù)值定義成默認(rèn)參
數(shù)即可,就像下面這樣:
>>> 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
>>>