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

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

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

def __mul__(self, other):
    match type(other):
        case int | float:
            pass
        case Vector2:
            pass

如果我运行这个,我会得到

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

如果我删除

 | float
它仍然无法工作,所以我不能将它们分开。

types pattern-matching python-3.10
2个回答
13
投票

带有变量的情况(例如:

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

类型可以在案例中使用,但意味着

isinstance()
,测试以确定匹配的值是否是该类型的实例。因此,用于匹配的值应该是实际变量
other
而不是类型
type(other)
,因为
type(other)
是一种类型,其类型将与
type()
匹配。

def __mul__(self, other):
    match other:
        case int() | float():
            pass
        case Vector2():
            pass

0
投票

因为这是“如何使用匹配大小写来检查 python 中的变量类型?”的第一个结果这可能会回答您以及许多其他问题(Python 3.10+):

def print_type(v):
    match v:
        # None must come before int
        case None:
            print("NONE")
        # bool() must come before int
        case bool():
            print("BOOL")
        case int():
            print("INT")
        case float():
            print("FLOAT")
        case Vector2():
            print("VECTOR2")
        case str():
            print("STR")

示例:

print_type(1)  # prints INT
a = 1
print_type(a)  # prints INT
print_type(None)  # prints NONE
print_type("Hello")  # prints STR
v = Vector2()
print_type(v)  # prints VECTOR2

文档中阅读更多相关信息(感谢:@charelf)

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