Vertical bar in Python bitwise assignment operator

前端 未结 4 788
情话喂你
情话喂你 2020-12-17 09:07

There is a code and in class\' method there is a line:

object.attribute |= variable

I can\'t understand what it means. I didn\'t find (|=)

4条回答
  •  遥遥无期
    2020-12-17 09:17

    For an integer this would correspond to Python's "bitwise or" method. So in the below example we take the bitwise or of 4 and 1 to get 5 (or in binary 100 | 001 = 101):

    Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
        >>> a = 4
        >>> bin(a)
        '0b100'
        >>> a |= 1
        >>> bin(a)
        '0b101'
        >>> a
        5
    

    More generalised (as Alejandro says) is to call an object's or method, which can be defined for a class in the form:

    def __or__(self, other):
        # your logic here
        pass
    

    So in the specific case of an integer, we are calling the or method which resolves to a bitwise or, as defined by Python.

提交回复
热议问题