Python3 函数
函数定义与调用、参数传递、默认/可变/关键字参数、匿名函数与 return。
定义一个函数
Define a function with def: name, parenthesised parameter list, colon, then an indented body. Functions are objects — assignable and passable like any value.
def hello():
print("Hello, World!")
hello()
print(type(hello))
print(hello.__name__)Hello, World!
<class 'function'>
hello函数调用
Call with the name plus parentheses, passing arguments positionally or by keyword. A function without return yields None; return also exits early.
def printme(s):
print(s)
return
printme("call the function")
printme("call again")
def check(x):
if x < 0:
return "negative"
return "non-negative"
print(check(-1), check(0))
print(printme("returns None"))call the function
call again
negative non-negative
returns None
None参数传递
Python passes object references. Rebinding an immutable argument (number, string, tuple) inside the function leaves the caller untouched; mutating a mutable one (list, dict) in place is visible outside.
def change(num, lst):
num = 99
lst.append(4)
a = 1
b = [1, 2, 3]
change(a, b)
print(a, b)
print(id(a) == id(1))1 [1, 2, 3, 4]
True参数
Five parameter kinds: positional, default, variadic positional *args, keyword-only, variadic keyword **kwargs. The order is fixed: positional → default → *args → keyword-only → **kwargs.
def f(a, b=2, *args, **kwargs):
print("a=%r b=%r args=%r kwargs=%r" % (a, b, args, kwargs))
f(1)
f(1, 3, 4, 5, k=6)
def g(*, name):
return "hi " + name
print(g(name="py"))
def h(a, b, /, c):
return a + b + c
print(h(1, 2, c=3))a=1 b=2 args=() kwargs={}
a=1 b=3 args=(4, 5) kwargs={'k': 6}
hi py
6def f(x, acc=[]) shares one list across calls — use acc=None and create the list inside instead.匿名函数
lambda builds an anonymous function from a single expression whose value is returned. It shines as a throwaway callback for key=, sorted, map, filter.
f = lambda x, y: x + y
print(f(3, 4))
print((lambda x: x ** 2)(5))
pairs = [(1, 'b'), (2, 'a')]
pairs.sort(key=lambda p: p[1])
print(pairs)
print(list(map(lambda x: x * 2, [1, 2, 3])))
print(list(filter(lambda x: x % 2 == 0, range(6))))7
25
[(2, 'a'), (1, 'b')]
[2, 4, 6]
[0, 2, 4]return 语句
return ends the function and hands back a value; bare return means None. Multiple values are packed into a tuple and can be unpacked at the call site.
def div(a, b):
if b == 0:
return None
return a / b
print(div(6, 3))
print(div(1, 0))
def multi():
return 1, 2
x, y = multi()
print(multi(), x, y)2.0
None
(1, 2) 1 2强制位置参数
Since Python 3.8, / marks positional-only parameters (before it) and * marks keyword-only ones (after it). This stops callers depending on names, so you can rename them later.
def kw_only(a, b, /, c, d, *, e, f):
print(a, b, c, d, e, f)
kw_only(1, 2, 3, d=4, e=5, f=6)
try:
kw_only(a=1, b=2, c=3, d=4, e=5, f=6)
except TypeError as ex:
print("TypeError:", ex)1 2 3 4 5 6
TypeError: kw_only() got some positional-only arguments passed as keyword arguments: 'a, b'定义一个函数
用 def 定义函数:函数名、括号内的参数列表、冒号,然后缩进的函数体。函数也是对象,可以赋值给变量、作为参数传递。
def hello():
print("Hello, World!")
hello()
print(type(hello))
print(hello.__name__)Hello, World!
<class 'function'>
hello函数调用
用函数名加括号调用,括号里按位置或关键字传参。没有 return 的函数返回 None;return 可以提前结束函数。
def printme(s):
print(s)
return
printme("call the function")
printme("call again")
def check(x):
if x < 0:
return "negative"
return "non-negative"
print(check(-1), check(0))
print(printme("returns None"))call the function
call again
negative non-negative
returns None
None参数传递
Python 是「传对象引用」:传入不可变对象(数字、字符串、元组)时,函数内重新赋值不影响外部;传入可变对象(列表、字典)时就地修改会影响外部。
def change(num, lst):
num = 99
lst.append(4)
a = 1
b = [1, 2, 3]
change(a, b)
print(a, b)
print(id(a) == id(1))1 [1, 2, 3, 4]
True参数
参数形式有五种:位置参数、默认参数、可变位置参数 *args、关键字参数、可变关键字参数 **kwargs。顺序固定为「位置 → 默认 → *args → 仅关键字 → **kwargs」。
def f(a, b=2, *args, **kwargs):
print("a=%r b=%r args=%r kwargs=%r" % (a, b, args, kwargs))
f(1)
f(1, 3, 4, 5, k=6)
def g(*, name):
return "hi " + name
print(g(name="py"))
def h(a, b, /, c):
return a + b + c
print(h(1, 2, c=3))a=1 b=2 args=() kwargs={}
a=1 b=3 args=(4, 5) kwargs={'k': 6}
hi py
6def f(x, acc=[]) 会让所有调用共享同一个列表,正确写法是 acc=None 再在函数内 if acc is None: acc = []。匿名函数
lambda 创建只有单个表达式的匿名函数,返回值就是表达式结果。它最适合作为 key、sorted、map、filter 的一次性小函数。
f = lambda x, y: x + y
print(f(3, 4))
print((lambda x: x ** 2)(5))
pairs = [(1, 'b'), (2, 'a')]
pairs.sort(key=lambda p: p[1])
print(pairs)
print(list(map(lambda x: x * 2, [1, 2, 3])))
print(list(filter(lambda x: x % 2 == 0, range(6))))7
25
[(2, 'a'), (1, 'b')]
[2, 4, 6]
[0, 2, 4]return 语句
return 结束函数并返回值;不带值等价于返回 None。返回多个值时实际返回一个元组,调用处可以直接解包。
def div(a, b):
if b == 0:
return None
return a / b
print(div(6, 3))
print(div(1, 0))
def multi():
return 1, 2
x, y = multi()
print(multi(), x, y)2.0
None
(1, 2) 1 2强制位置参数
Python 3.8 起用 / 标记仅位置参数(在其之前),用 * 标记仅关键字参数(在其之后)。这能防止调用方依赖参数名,方便日后改名而不破坏接口。
def kw_only(a, b, /, c, d, *, e, f):
print(a, b, c, d, e, f)
kw_only(1, 2, 3, d=4, e=5, f=6)
try:
kw_only(a=1, b=2, c=3, d=4, e=5, f=6)
except TypeError as ex:
print("TypeError:", ex)1 2 3 4 5 6
TypeError: kw_only() got some positional-only arguments passed as keyword arguments: 'a, b'