我有一个类,我希望在某些情况下能够对其进行按位运算。
class Measurement(object):
def __init__(self, value = None, category = None, measure = None):
self.value = value
self.category = category
self.measure = measure
def __nonzero__(self):
return self.value.__nonzero__()
def __or__(self, other):
return self.__nonzero__() | other
a = False
b = Measurement(True)
此时c = b | a
有效,但是 c = a | b
给出类型错误。我如何让它双向工作?
此外,是否有更优雅的方式来做到这一点?例如,我曾希望通过定义 __nonzero__
,我可能会得到正确的行为,但事实并非如此。
我正在使用 Python 2.7。
最佳答案
通过同时定义 __ror__
,如下所示,我得到了正确的行为。然而,问题的第二部分仍然存在。有没有更优雅的方式?
def __ror__(self, other):
return self.__or__(other)
关于python - 重载按位运算符以在 Python 中使用 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41598203/