Python in Class in the __contains __ (self, x) function parses

Internet search a number of articles, bit around.

Add __contains __ (self, x) in the function may be performed in Class li operate on instances of the object class.

The following code

class Graph():
    def __init__(self):
        self.items = {'a':1,'b':2,'c':3}

    def __str__(self):
        return '打印我干嘛'
    
    def __contains__(self,x): # 判断一个定点是否包含在里面
        return x in self.items



a = Graph()
print('a' in a) # 通过在类中添加 __contains__ , 可以实现 Class实例化的对象 进行 in 操作
print('d' in a) # 通过在类中添加 __contains__ , 可以实现 Class实例化的对象 进行 in 操作

>> True
>> False

Guess you like

Origin www.cnblogs.com/gtscool/p/12074427.html