如何使用大小写匹配来检查Python中的变量类型?

Zac*_*ner 11 types pattern-matching python-3.10

我有这段代码来检查变量在乘法时是否是Vector2我的Vector2类中的数字或 a 。

def __mul__(self, other):
    match type(other):
        case int | float:
            pass
        case Vector2:
            pass
Run Code Online (Sandbox Code Playgroud)

如果我运行这个,我会得到SyntaxError: name capture 'int' makes remaining patterns unreachable,当我将鼠标悬停在 vscode 中时,它会给我:

"int" is not accessed
Irrefutable pattern allowed only as the last subpattern in an "or" pattern
All subpatterns within an "or" pattern must target the same names
Missing names: "float"
Irrefutable pattern is allowed only for the last case statement
Run Code Online (Sandbox Code Playgroud)

如果我删除 | float它仍然不起作用,所以我不能将它们分开。

Rob*_*com 19

带有变量的情况(例如:case _:case other:)需要是case列表中的最后一个。它匹配任何值(如果该值与先前的情况不匹配),并在变量中捕获该值。

类型可以在案例中使用,但意味着isinstance()要进行测试以确定匹配的值是否是该类型的实例。因此,用于匹配的值应该是实际变量other而不是类型type(other),因为type(other)是其类型将匹配的类型type()

def __mul__(self, other):
    match other:
        case int() | float():
            pass
        case Vector2():
            pass
Run Code Online (Sandbox Code Playgroud)

  • 这种模式称为类模式:“类模式提供对解构任意对象的支持”。更多信息可以在文档中找到:https://peps.python.org/pep-0622/#class-patterns (4认同)