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)