Python3 函数

函数定义与调用、参数传递、默认/可变/关键字参数、匿名函数与 return。

Beginner
Key Pointsdef 定义函数,参数默认值只求值一次(勿用可变对象);*args 收位置参数、**kwargs 收关键字参数,/ 与 * 可强制参数传递方式。

定义一个函数

Define a function with def: name, parenthesised parameter list, colon, then an indented body. Functions are objects — assignable and passable like any value.

Python
def hello():
    print("Hello, World!")

hello()
print(type(hello))
print(hello.__name__)
Output
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.

Python
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"))
Output
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.

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))
Output
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.

Python
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))
Output
a=1 b=2 args=() kwargs={}
a=1 b=3 args=(4, 5) kwargs={'k': 6}
hi py
6
Default arguments are evaluated once at definition time. def 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.

Python
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))))
Output
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.

Python
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)
Output
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.

Python
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)
Output
1 2 3 4 5 6
TypeError: kw_only() got some positional-only arguments passed as keyword arguments: 'a, b'

Friends & Partners