首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用匹配用例检查python中的变量类型?

如何使用匹配用例检查python中的变量类型?
EN

Stack Overflow用户
提问于 2022-04-23 18:24:42
回答 1查看 1.4K关注 0票数 3

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

代码语言:javascript
运行
复制
def __mul__(self, other):
    match type(other):
        case int | float:
            pass
        case Vector2:
            pass

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

代码语言:javascript
运行
复制
"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,它仍然不能工作,所以我不能将它们分开。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-31 16:26:38

变量(例如:case _:case other:)的大小写需要是列表中的最后一个case。它匹配任何值,其中的值不是由以前的情况匹配的,并在变量中捕获该值。

一个类型可以在一种情况下使用,但暗示isinstance(),测试以确定所匹配的值是否是该类型的实例。因此,用于匹配的值应该是实际变量other,而不是type(other)类型,因为type(other)是一个类型与type()匹配的类型。

代码语言:javascript
运行
复制
def __mul__(self, other):
    match other:
        case int() | float():
            pass
        case Vector2():
            pass
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71982525

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档