python的match语法与海象语法

match语法

match语法是python3.10引入的,用于替代if-elif-else的语法,使代码更加简洁易读。

1
2
3
4
5
6
7
8
9
10
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something is wrong with the internet"

等同于:

1
2
3
4
5
6
7
8
9
def http_error(status):
if status == 400:
return "Bad request"
elif status == 404:
return "Not found"
elif status == 418:
return "I'm a teapot"
else:
return "Something is wrong with the internet"

match语法的好处是可以在一个语句中匹配多个条件,而不需要使用多个if-elif-else语句。因此,match语法可以使代码更加简洁易读。

海象语法

海象语法是python3.8引入的,用于在表达式中赋值,使代码更加简洁易读。可以在if、while、for等语句中使用。案例:

1
2
if (n := len(a)) > 10:
print(n)

等同于:

1
2
3
n = len(a)
if n > 10:
print(n)

海象语法在循环中也可以使用,例如:

1
2
while (n := len(a)) > 10:
print(n)

等同于:

1
2
3
4
n = len(a)
while n > 10:
print(n)
n = len(a)

海象语法的好处是可以在表达式中直接赋值,而不需要先赋值再使用。因此,海象语法可以使代码更加简洁易读。