如何修复 TypeError: 调用的匹配模式必须是 Python 3.10 中的类型

问题描述 投票:0回答:3

尝试学习Python 3.10模式匹配。阅读 8.6.4.9 后尝试了这个例子。映射模式

>>> match 0.0:
...  case int(0|1):
...   print(1)
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: called match pattern must be a type
>>>

特别是关于内置类型的注释,包括 int。我应该如何编码来测试整数值 0 或 1(文档中的示例)而不出现此错误?

pattern-matching python-3.10
3个回答
7
投票

我陷入了困境:

match 0.0
  case int:
    print(1)

有效地重新定义了 int,所以下次我尝试发布的匹配时,它失败了,因为 my int 遮盖了内置


5
投票

对于结构模式匹配,类模式需要在类名称两边加上括号。

例如:

x = 0.0
match x:
    case int():
        print('I')
    case float():
        print('F')
    case _:
        print('Other')

0
投票

我应该如何编码来测试整数值 0 或 1

正确的答案是使用OR-Patterns,如PEP 622中所述:

可以使用 | 将多个替代模式组合成一个。这 表示如果至少有一个替代项匹配,则整个模式匹配。 从左到右尝试替代品并有短路 属性,如果匹配则不会尝试后续模式

x = 1
match x:
    case int(0 | 1):
        print('case of x = int(0) or x = int(1)')
    case _:
        print('x != 1 or 0')

输出:'x = int(0) 或 x = int(1) 的情况'

类型不敏感会像这样:

x = 1.0
match x:
    case 0 | 1:
        print('case of x = 0 or x = 1')
    case _:
        print('x != 1 or 0')

输出:'x = 0 或 x = 1 的情况'


如果您想单独检查每个案例,您可以这样做:

x = 1.0
match x:
    case int(0):
        print('x = 0')
    case int(1):
        print('x = 1')
    case _:
        print('x != 1 or 0')

输出:

x != 1 or 0

x = 1.0
match x:
    case 0:
        print('x = 0')
    case 1:
        print('x = 1')
    case _:
        print('x != 1 or 0')

输出:

x = 1

© www.soinside.com 2019 - 2024. All rights reserved.