简体   繁体   English

布尔运算符的python扩充分配

[英]python augmented assignment for boolean operators

Does Python have augmented assignment statements corresponding to its boolean operators? Python是否具有与其布尔运算符相对应的扩充赋值语句?

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? 为了避免两次写“ x”?

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. 请注意,我知道使用&=的语句,但我一直在寻找一个适用于y为任何类型的语句,而不仅仅是y为布尔值的语句。

The equivalent expression is &= for and and |= for or . 等价表达是&=用于and|=用于or

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

Note bitwise AND and bitwise OR and will only work (as you expect) for bool types. 请注意bitwise ANDbitwise OR并且仅对bool类型有效(如您期望的那样)。 bitwise AND is different than logical AND for other types, such as numeric bitwise AND logical AND其他类型(例如数字)的logical AND不同

>>> 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. 请参阅这篇文章 ,以更全面地讨论这种情况下按位与逻辑运算。

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. 对于x = x and y你要么重新绑定xx ,或者你把它重新绑定到y ,但x 本身不会改变。

As such, x and= y would actually be quite confusing; 因此, x and= y实际上会很混乱; either x would be unchanged, or replaced by y . x将保持不变,或被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. 仅对于布尔对象(因此TrueFalse ),这些运算符将被重载以产生与andor运算符相同的输出。 For other types they'll either result in a TypeError , or an entirely different operation is applied. 对于其他类型,它们要么导致TypeError ,要么应用完全不同的操作。 For integers, that's a bitwise operation, sets overload it to do intersections. 对于整数,这是按位运算,将其设置为重载以进行交集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM