一般来说,在
<type>(arg1=value1)
语句中的
<type>(attr1=value1)
期间,代码case
会更改为代码
match
。这允许进行一些非常有趣和复杂的捕获。
例如,我们可以问 “我的实例是否有一个名为‘排序’的属性,如果有的话捕获它”:
match [1,2,3]:
case list(sort=f): # this isn't a call, it is an attr-capture statement
print(f)
由于列表实例的第一个(也是唯一的)位置参数是列表值,因此您也可以捕获这些项目:
match [1,2,3]:
case list((x,*y),sort=f): # here we are capturing the 'attr' called 'sort' as 'f'
print(x,y,f)
同样,您可以指定匹配值,而不是将它们捕获到变量中:
g = list.sort
match [1,2,3]:
case list((1,*y),sort=g): # here we ask if the attr 'sort' is the same as 'g'
print(y)
但是,我现在对以下内容感到困惑:
match [1,2,3]:
case list(x,sort=list.sort): # fails to match, but why???
print(x)
我本以为这会失败,因为
list.sort
的含义与指定“‘列表’的‘排序’函数”不同。也许sort=list.sort
意味着“我是否有一个名为“排序”的属性,它本身是“类型”“列表”,它也有一个名为“排序”的属性”。所以我尝试了:
match [1,2,3]:
case list.sort: # also fails, why?
print('ya')
所以,list.sort
并不意味着我想要带有排序属性的类型列表。所以,然后我尝试了:
match list.sort:
case list.sort: # does match, wait, what?
print('ya')
这有效。那么,在 list.sort
does
期间,
case
的意思是从 sort
的类型中使用
list
的功能,但是为什么
list(sort=list.sort)
会失败呢?
class P:
def __init__(self,a,b):
self.x,self.y = a+b,a-b
match P(5,6):
case P(x=11,y=a): # a is a new variable, 11 is a match
print(a)
list.sort
是一个描述符,因此它不会与
sort=
匹配,后者将是方法或函数。可以看到
f
的类型是内置方法:
match [1,2,3]:
case list(x,*y), sort=f): # inspect the capture of `sort` as `f`
print('match', f) # match <built-in method sort of list object at 0x104d94c80>
但是list.sort
的类型不是:
>>> type(list.sort)
method_descriptor
您可以通过首先从实例化列表对象中提取描述符指向的实际排序方法来解决此问题:
real_list_sort = list().sort
print(type(real_list_sort)) # builtin_function_or_method
match [1, 2, 3]:
case list((x, *y), sort=real_list_sort):
print('matched')