In [1]:
%matplotlib inline
# 多行结果输出支持
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
In [2]:
# 可变参数 packing and unpacking
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
Out[2]:
Out[2]:
In [3]:
# 如果你还希望某个函数能同时接受任意数量的位置参数和关键字参数,可以同时使用*和**
# 使用这个函数时,所有位置参数会被放到args元组中,所有关键字参数会被放到字典kwargs中
def anyargs(*args, **kwargs):
print(args) # A tuple
print(kwargs) # A dict
In [4]:
arg1 = 1, 2, 4
arg2 = {'q': 2, 'a': 3}
anyargs(*arg1, **arg2)
def a(x, *args, y):
pass
def b(x, *args, y, **kwargs):
pass
In [5]:
def recv(maxsize, *, block):
'Receives a message'
print(maxsize)
recv(1024, True) # TypeError
In [6]:
recv(1024, block=True) # Ok
In [7]:
# 参数的默认值是None的意思是可以没有
def minimum(*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
Out[7]:
Out[7]:
__annotations__
属性中 func.__annotations__
In [8]:
def add(x:int, y:int) -> int:
return x + y
In [9]:
# Using a list as a default value
# 可变的默认参数使用 None 作为默认值
def spam(a, b=None):
# 这里使用 is
if b is None:
b = []
pass
In [13]:
y = lambda x, y: x ** y
In [14]:
y(2, 3)
Out[14]:
In [15]:
names = ['David Beazley', 'Brian Jones',
'Raymond Hettinger', 'Ned Batchelder']
sorted(names, key=lambda name: name.split()[-1].lower())
Out[15]:
In [20]:
'David Beazley'.split()[-1].lower()
Out[20]:
In [22]:
x = 10
a = lambda y: x + y
x = 20
b = lambda y: x + y
In [23]:
a(10)
Out[23]:
In [24]:
b(10)
Out[24]:
In [26]:
x = 10
a = lambda y, x=x: x + y
x = 20
b = lambda y, x=x: x + y
In [27]:
a(10)
Out[27]:
In [28]:
b(10)
Out[28]:
通过使用函数默认值参数形式,lambda函数在定义时就能绑定到值
In [29]:
def spam(a, b, c, d):
print(a, b, c, d)
In [30]:
from functools import partial
s2 = partial(spam, d=3)
In [31]:
s2(1, 2, 3)
In [ ]: