Python a &= b meaning?

前端 未结 5 1400
萌比男神i
萌比男神i 2020-12-31 10:55

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

5条回答
  •  灰色年华
    2020-12-31 11:53

    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
    

提交回复
热议问题