带括号和不带括号的python断言

编程入门 行业动态 更新时间:2024-10-10 03:31:02
本文介绍了带括号和不带括号的python断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

以下是四个简单的 assert 调用:

>>>断言 1==2回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 ?断言错误>>>断言 1==2,嗨"回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 ?断言错误:嗨>>>断言(1==2)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 ?断言错误>>>断言(1==2,嗨")

请注意,最后一个不会引发错误.带括号或不带括号的 assert 调用导致这种行为有什么区别?我的做法是用括号,但是上面的建议我不应该.

解决方案

最后一个 assert 会给你一个警告(SyntaxWarning: assertion is always true, 也许去掉括号?code>) 如果你通过一个完整的解释器运行它,而不是通过 IDLE.因为 assert 是关键字而不是函数,所以您实际上是传入一个元组作为第一个参数,而忽略了第二个参数.

回想一下,非空元组的计算结果为 True,并且由于断言消息是可选的,因此您在编写 assert(1==2,嗨").

Here are four simple invocations of assert:

>>> assert 1==2 Traceback (most recent call last): File "<stdin>", line 1, in ? AssertionError >>> assert 1==2, "hi" Traceback (most recent call last): File "<stdin>", line 1, in ? AssertionError: hi >>> assert(1==2) Traceback (most recent call last): File "<stdin>", line 1, in ? AssertionError >>> assert(1==2, "hi")

Note that the last one does not raise an error. What is the difference between calling assert with or without parenthesis that causes this behavior? My practice is to use parenthesis, but the above suggests that I should not.

解决方案

The last assert would have given you a warning (SyntaxWarning: assertion is always true, perhaps remove parentheses?) if you ran it through a full interpreter, not through IDLE. Because assert is a keyword and not a function, you are actually passing in a tuple as the first argument and leaving off the second argument.

Recall that non-empty tuples evaluate to True, and since the assertion message is optional, you've essentially called assert True when you wrote assert(1==2, "hi").

更多推荐

带括号和不带括号的python断言

本文发布于:2023-11-29 02:31:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644948.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:括号   断言   不带   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!