Is there any builtin Python value where truth evaluation is invalid?(是否有任何内置的 Python 值,其中真值评估无效?)
问题描述
我有一组子类,它们都应该定义一个属性 x
,该属性应该评估为 True 或 False.为了在我忘记在子类中设置此值时捕获错误,我想在其超类中将其设置为真值评估导致错误的值.Python 中是否有具有这种行为的内置值?我有点期望 NotImplemented
有这种行为,但它的评估结果为 True
.
I have a set of sub-classes that should all define an attribute x
that should either evaluate to True or False. In order to catch bugs when I forget to set this value in a subclass, I would like to set it in its superclass to a value for which truth evaluation results in an error. Is there any built-in value in Python with this behaviour? I sort of expected NotImplemented
to have this behaviour, but it evaluates to True
.
我可以将它设置为 numpy.array([0, 0])
其中 if x:
引发 ValueError
,但感觉不对.同样,我可以定义自己的类,其中 __bool__
引发异常.但是是否有适合此目的的内置值?
I could set it to numpy.array([0, 0])
where if x:
raises ValueError
, but that feels wrong. Likewise, I could define my own class where __bool__
raises an exception. But is there any built-in value appropriate for this purpose?
其他选择是设置一个属性(抽象与否)或根本不定义它(所以我们获取 AttributeError
).
Other alternatives would be to set a property (abstract or not) or to not define it at all (so we get AttributeError
).
推荐答案
以后,NotImplemented
将在布尔上下文中无效.
In the future, NotImplemented
will be invalid in a boolean context.
从 Python 3.9 开始,不推荐在布尔上下文中使用 NotImplemented
.来自文档:
Starting with Python 3.9, using NotImplemented
in a boolean context is deprecated. From the documentation:
不推荐在布尔上下文中评估 NotImplemented
.虽然它当前评估为 true,但它会发出 DeprecationWarning
.它将在 Python 的未来版本中引发 TypeError
.
Evaluating
NotImplemented
in a boolean context is deprecated. While it currently evaluates as true, it will emit aDeprecationWarning
. It will raise aTypeError
in a future version of Python.
截至 2020 年 10 月 6 日,Python 的未来版本(据我所知)尚未确定,但在未来某个时间点(我预计不会在 Python 3.11 之前),未实现
将成为真值评估无效的 Python 内置值.
As of 2020-10-06, that future version of Python has (as far as I know) not been determined, but at some point in the future (I'd expect not before Python 3.11), NotImplemented
will become a builtin Python value where truth evaluation is invalid.
这篇关于是否有任何内置的 Python 值,其中真值评估无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否有任何内置的 Python 值,其中真值评估无效?
基础教程推荐
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 筛选NumPy数组 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01