Python运算符| =含义

时间:2015-04-01 19:56:36

标签: python

由于python的一些版本控制问题,我必然会使用自定义函数来比较HMAC(SHA512)。为此我发现了这个功能:

def compare_digest(x, y):
    if not (isinstance(x, bytes) and isinstance(y, bytes)):
        logfile.debug("both inputs should be instances of bytes")
    if len(x) != len(y):
        return False
    result = 0
    for a, b in zip(x, y):
        result |= a ^ b
    return result == 0

我在Django中使用它,因此我创建了一个记录器(logfile),可以将调试消息保存到文件中。

代码在此步骤中断:

result |= a ^ b

但是,我不知道| =运算符代表什么,这里发生了什么。如果有人可以解释这个我可以尝试重写这个。

我的python版本(不幸的是2.7.4)和2.7.7我没有问题,因为该函数已经正确移植并可用。

2 个答案:

答案 0 :(得分:17)

|是按位OR运算符。 |=+=-=等的按位OR等价物。基本上,a |= ba = a | b的简写。

答案 1 :(得分:0)

在一个步骤中逐位或分配。有点像

a+=1 # which means a = a + 1