What does the &= operator mean in Python, and can you give me a working example?
I am trying to understand the __iand__ operator.
I just d
Contrary to some of the other answers, a &= b is not shorthand for a = a & b, though I admit it often behaves similarly for built-in immutable types like integers.
a &= b can call the special method __iand__ if available. To see the difference, let's define a custom class:
class NewIand(object):
def __init__(self, x):
self.x = x
def __and__(self, other):
return self.x & other.x
def __iand__(self, other):
return 99
After which we have
>>> a = NewIand(1+2+4)
>>> b = NewIand(4+8+16)
>>> a & b
4
>>> a = a & b
>>> a
4
but
>>> a = NewIand(1+2+4)
>>> b = NewIand(4+8+16)
>>> a &= b
>>> a
99