Ray*_*ger 38 python isinstance python-3.10 structural-pattern-matching
我想转换此现有代码以使用模式匹配:
if isinstance(x, int):
pass
elif isinstance(x, str):
x = int(x)
elif isinstance(x, (float, Decimal)):
x = round(x)
else:
raise TypeError('Unsupported type')
Run Code Online (Sandbox Code Playgroud)
如何使用模式匹配编写检查,以及如何同时isinstance测试多种可能的类型?(float, Decimal)
Ray*_*ger 55
这是使用match和case 的等效代码:
match x:
case int():
pass
case str():
x = int(x)
case float() | Decimal():
x = round(x)
case _:
raise TypeError('Unsupported type')
Run Code Online (Sandbox Code Playgroud)
PEP 634指定isinstance()检查是使用类模式执行的。要检查str的实例,请写入case str(): ...。请注意,括号是必不可少的。这就是语法如何确定这是一个类模式。
为了一次检查多个类,PEP 634 提供了使用运算符的 or 模式|。例如,要检查对象是否是float或Decimal的实例,请 write case float() | Decimal(): ...。和以前一样,括号是必不可少的。