7. 成员检测运算符重载

成员检测运算符有两个:

  1. in运算符。
  2. not in 运算符。

这两个运算符互为布尔非的关系。

成员检测运算符重载只有一个对应方法: __contains__

成员检测运算符重载方法格式

class 类名: 
    def __contains__(self, item):
        ...

运算符和方法

方法名
运算符和表达式
说明
__contains__(self, item)
item in self
成员检测运算

item not in self 运算等同于 not (item in self) 运算。

示例

# 成员检测运算符重载 示例

class Vector3D:
    '''用于描述三维向量的类!,x,y,z分别是向量的坐标位置!'''
    def __init__(self, x, y, z):
        self.x, self.y, self.z = x, y, z

    def __repr__(self):
        return f'Vector3D({self.x},{self.y},{self.z})'

    def __contains__(self, item):
        ''' in 运算符的重载方法 '''
        print("item:", item)
        if item == self.x or item == self.y or item == self.z:
            return True
        return False

v1 = Vector3D(1, 2, 3)
print('v1:', v1)
print(3 in v1)
print(100 not in v1)

运行结果

v1: Vector3D(1,2,3)
item: 3
True
item: 100
True

成员检测运算符重载说明