python - 重载按位运算符以在 Python 中使用 bool 值

标签 python python-2.7

我有一个类,我希望在某些情况下能够对其进行按位运算。

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/

相关文章:

python - 如何通过在Python中的某些列上应用条件来过滤csv数据

python - 在 Windows 10 上为 Python 3 安装 OpenCV

Python 将数据分组为一小时间隔

python - DLL 加载失败 : The specified module could not be found PYTHON

python - “chalice deploy”调用以“Unknown parameter in input: ”结尾

python - 介绍屏幕未加载

python - 在 Python 中,如何将 `datetime` 对象转换为秒?

python - 如果我希望用户输入的数据具有特定格式,如何在python 3中设置格式检查?

python - 如何在 python 中使用 hex()?

image - pygame 1.9 似乎没有加载 png