python augmented assignment for boolean operators

China☆狼群 提交于 2019-12-06 03:24:59

问题


Does Python have augmented assignment statements corresponding to its boolean operators?

For example I can write this:

x = x + 1

or this:

x += 1

Is there something I can write in place of this:

x = x and y

To avoid writing "x" twice?

Note that I'm aware of statements using &= , but I was looking for a statement that would work when y is any type, not just when y is a boolean.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/26409572/python-augmented-assignment-for-boolean-operators

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