我有一组子类,它们都应该定义一个属性x
,该属性应该计算为True或False。当我忘记在子类中设置此值时,为了捕获bug,我想在其超类中将其设置为真值计算导致错误的值。Python中有任何内置值具有此行为吗?我有点期望NotImplemented
有这种行为,但它的计算结果是True
。
我可以将其设置为numpy.array([0, 0])
,其中if x:
提高ValueError
,但这感觉不对。同样,我可以定义自己的类,其中__bool__
引发异常。但是是否存在适合于此目的的内置值呢?
其他选择是设置属性(抽象或非抽象)或根本不定义它(所以我们得到AttributeError
)。
我最近遇到了同样的问题,只是用例略有不同:
我有一个带有flag属性的类,其值由调用者传递给__init__
。类的对象可以从两个不同版本的数据创建,其中旧版本的数据不包含确定标志是True
还是False
所需的信息。
将另一个bol值设置为None
(这是表示丢失数据的常用方法)将不起作用,因为None
会愉快地计算为False
。
和你一样,我也没有找到一个令人满意的内置解决方案,所以我自己写了一个。
(为python2.7编写,但很容易调整为python3)
class NotTrueNorFalseType(object):
"""
A singleton class whose instance can be used in place of True or False, to represent
a value which has no true-value nor false-value, e.g. a boolean flag the value of
which is unknown or undefined.
"""
def __new__(cls, *args, **kwargs):
# singleton
try:
obj = cls._obj
except AttributeError:
obj = object.__new__(cls, *args, **kwargs)
cls._obj = obj
return obj
def __nonzero__(self):
raise TypeError('%s: Value is neither True nor False' % self)
def __repr__(self):
return 'NotTrueNorFalse'
NotTrueNorFalse = NotTrueNorFalseType()
这个类的设计(min-)决定受到None
单例的启发(例如命名单例实例"Foo"和类"FooType",从__repr__
返回"Foo",在无效操作时引发TypeError
)。
以后,NotImplemented
将在布尔上下文中无效。
从Python 3.9开始,不赞成在布尔上下文中使用NotImplemented
。来自文档:
不赞成在布尔上下文中计算
NotImplemented
。虽然它当前的计算结果为true,但它将发出一个DeprecationWarning
。它将在Python的未来版本中引发TypeError
。
截至2020-10-06,Python的未来版本尚未确定(据我所知),但在未来的某个时候(我预计不会在Python 3.11之前),NotImplemented
将成为一个内置的Python值,其中真值计算无效。