布尔运算符的python扩充分配 [英] python augmented assignment for boolean operators

查看:111
本文介绍了布尔运算符的python扩充分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python是否具有与其布尔运算符相对应的扩充赋值语句?

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

例如,我可以这样写:

x = x + 1

或者这个:

x += 1

有什么可以代替的吗?

x = x and y

为避免两次写"x"?

请注意,我知道使用& =的语句,但我一直在寻找一个适用于y为任何类型的语句,而不仅限于y为布尔值的语句.

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.

推荐答案

不,没有增强的赋值运算符"rel =" nofollow> boolean运算符.

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

存在增强的赋值,使可变的左手操作数有机会就地更改对象,而不是创建新对象.另一方面,布尔运算符不能转换为就地运算;不能将其转换为就地运算.对于x = x and y,您可以将x重新绑定到x,或者将其重新绑定到y,但是x 本身不会改变.

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 and= y实际上会非常混乱; x将保持不变,或被y替换.

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.

这篇关于布尔运算符的python扩充分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆