5. 位运算符重载

位运算符重载

运算符和方法

方法名
运算符和表达式
说明
__invert__(self)
~ self
取反(一元运算
__and__(self, other)
self & other
位与
__or__(self, other)
self | other
位或
__xor__(self, other)
self ^ other
位异或
__lshift__(self, other)
self << other
左移
__rshift__(self, other)
self >> other
右移

反向位运算符重载

运算符和方法

方法名
运算符和表达式
说明
__rand__(self, other)
other & self
位与
__ror__(self, other)
other | self
位或
__rxor__(self, other)
other ^ self
位异或
__rlshift__(self, other)
other << self
左移
__rrshift__(self, other)
other >> self
右移

增强赋值位运算符重载

运算符和方法

方法名
运算符和表达式
说明
__iand__(self, other)
self &= other
位与
__ior__(self, other)
self |= other
位或
__ixor__(self, other)
self ^= other
位异或
__ilshift__(self, other)
self <<= other
左移
__irshift__(self, other)
self >>= other
右移

示例

# 位运算符重载 示例
# http://weimingze.com

class Vector1D:
    '''用于描述一维向量的类!'''
    def __init__(self, x):
        self.x = x

    def __repr__(self):
        return f'Vector1D({self.x})'

    def __and__(self, other):  # &
        print('__and__:位与运算符重载')

    def __or__(self, other):  # |
        print('__or__:位或运算符重载')

    def __xor__(self, other):  # ^
        print('__xor__:位异或运算符重载')

    def __lshift__(self, other):  # <<
        print('__lshift__:左移运算符重载')

    def __rshift__(self, other):  # >>
        print('__rshift__:右移运算符重载')

v1 = Vector1D(100)
v2 = Vector1D(200)
v1 & v2
v1 | v2
v1 ^ v2
v1 << v2
v1 >> v2

运行结果

__and__:位与运算符重载
__or__:位或运算符重载
__xor__:位异或运算符重载
__lshift__:左移运算符重载
__rshift__:右移运算符重载