python 中的 |=(竖线等于)符号有什么作用?

What does |= (pipe equal) sign do in python?

我在项目中看到一段代码是这样写的:

 move = Move.create({
    'name': repair.name,
    'product_id': repair.product_id.id,
    'product_uom': repair.product_uom.id or repair.product_id.uom_id.id,
    'product_uom_qty': repair.product_qty,
    'partner_id': repair.address_id.id,
    'location_id': repair.location_id.id,
    'location_dest_id': repair.location_dest_id.id,
    'restrict_lot_id': repair.lot_id.id,
})
moves |= move
moves.action_done()

这里的|=是什么意思?

正如@AChampion 在第一个问题评论中已经提到的,它可能是 "bitwise or" 或 "set union"。虽然这个问题以 Odoo 作为上下文,但 Odoo class RecordSet.

"set union"

此 class 是在 Odoo 8 上与新的 API 一起引入的。对于其他运算符,请查看 Odoo 的官方文档。

简单来说就是moves = move | moves.

它是一个复合运算符,当你说:x |= y 它等同于 x = x | y

| 运算符表示 bitwise or 并且它在逐位级别对整数进行运算,这是一个示例:

a = 3    #                (011)
         #                 |||
b = 4    #                (100)
         #                 |||
a |= b   #<-- a is now 7  (111)

另一个例子:

a = 2    #                (10)
         #                 ||
b = 2    #                (10)
         #                 ||
a |= b   #<-- a is now 2  (10)

因此,如果两个源中的任何一个都设置了相同的位,则结果中的每个位都将被设置;如果两个源的那个位都为零,则结果中的每个位都将被设置为零。

管道也用在集上以获得并集:

a = {1,2,3}
b = {2,3,4}
c = {4,5,6}
print(a | b | c)  # <--- {1, 2, 3, 4, 5, 6}