python augmented assignment for boolean operators

三世轮回 提交于 2019-12-04 07:19:06

No, there is no augmented assignment operator for the boolean operators.

Augmented assignment exist to give mutable left-hand operands the chance to alter the object in-place, rather than create a new object. The boolean operators on the other hand cannot be translated to an in-place operation; for x = x and y you either rebind x to x, or you rebind it to y, but x itself would not change.

As such, x and= y would actually be quite confusing; either x would be unchanged, or replaced by y.

Unless you have actual boolean objects, do not use the &= and |= augmented assignments for the bitwise operators. Only for boolean objects (so True and False) are those operators overloaded to produce the same output as the and and or operators. For other types they'll either result in a TypeError, or an entirely different operation is applied. For integers, that's a bitwise operation, sets overload it to do intersections.

CoryKramer

The equivalent expression is &= for and and |= for or.

>>> b = True
>>> b &= False
>>> b
False

Note bitwise AND and bitwise OR and will only work (as you expect) for bool types. bitwise AND is different than logical AND for other types, such as numeric

>>> bool(12) and bool(5)   # logical AND
True

>>> 12 & 5    # bitwise AND
4

Please see this post for a more thorough discussion of bitwise vs logical operations in this context.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!