我有一组子类,它们都应该定义一个属性 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 值,其中真值评估无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!