与 int() 和 bool() 匹配
对于 Python 3.10.2,请考虑以下代码片段。
def print_type(v):
match v:
case int() as v:
s = f"int {v}"
case bool() as v:
s = f"bool {v}"
case _:
s = "other"
print(s)
尝试使用“s = False”,它将按预期打印“bool False”。现在反转 bool() 和 int() 的情况,结果现在将是“int False”。不完全符合我的预期。
这是一个错误吗?如果是的话,我会在 Python 论坛上发帖。
编辑
根据 trincot 的回答,这里是具有预期行为的代码版本。
def print_type(v):
match v:
case int() as v:
if isinstance(v, bool):
s = f"bool {v}"
else:
s = f"int {v}"
case _:
s = "other"
print(s)
With Python 3.10.2, consider this code snippet.
def print_type(v):
match v:
case int() as v:
s = f"int {v}"
case bool() as v:
s = f"bool {v}"
case _:
s = "other"
print(s)
Try it with 's = False' and it will print 'bool False' as expected. Now reverse the bool() and int() cases and the result will now be 'int False'. Not exactly what I expected.
Is it a bug? If so, I'll post on the Python forum.
EDIT
Based on trincot's answer, here is a version of the code that has the expected behavior.
def print_type(v):
match v:
case int() as v:
if isinstance(v, bool):
s = f"bool {v}"
else:
s = f"int {v}"
case _:
s = "other"
print(s)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,这不是一个错误。
bool
是int
的子类,因此每个布尔值也是一个整数。No, this is not a bug.
bool
is a subclass ofint
, and so every boolean is also an integer.