Why does the Python operator "& =" act differently than the operation "& =" is an integer?

Why is this set of s operation settings set? This does not work the same for an integer (bitwise) version of the same operator ....

Set operation &= (change s ):

 s = set('abc') t = set('bcd') u=s print u, s, t u &= t print u, s, t 

results:

 set(['a', 'c', 'b']) set(['a', 'c', 'b']) set(['c', 'b', 'd']) set(['c', 'b']) set(['c', 'b']) set(['c', 'b', 'd']) 

Bitwise operation &= (does not change s ):

 s = 7 t = 3 u=s print u, s, t u &= t print u, s, t 

Result:

 7 7 3 3 7 3 
+5
source share
1 answer

Integers implement the & operation, but not the &= operation, so when you use x &= y , it expands to x = x & y , which simply reassigns the variable x rather than changing its internal state (it will not "t & have it makes sense to change the mutation, as it does not make sense for + ). The same goes for freezons.

Defines the implementation of the &= operation, so it is not extended to reassign the variable, but rather changes the left side of the operator.

Tuples do not implement either & nor &= , so the error makes sense. However, you get the same effect with += : for tuples += expands, for lists it is a mutation in place, because lists are mutable.

Any class can implement its own version of these operators. See here for more details. In particular, & matches __and__ and &= before __iand__ .

If you think about it, this is a reasonable convention for mutable classes to implement operators in place to allow direct modification, but not immutable classes.

+5
source

Source: https://habr.com/ru/post/1247271/


All Articles