What does __contains__ do, what can call __contains__ function

前端 未结 5 850
鱼传尺愫
鱼传尺愫 2020-11-30 01:17

Here is my code:

class a(object):
    d=\'ffffd\'
    def __contains__(self):
        if self.d:return True
b=a()
print b.contains(\'d\')  # error
print contai         


        
5条回答
  •  时光取名叫无心
    2020-11-30 01:52

    Like all special methods (with "magic names" that begin and end in __), __contains__ is not meant to be called directly (except in very specific cases, such as up=calls to the superclass): rather, such methods are called as part of the operation of built-ins and operators. In the case of __contains__, the operator in question is in -- the "containment check" operator.

    With your class a as you present it (except for fixing your typo, and using True instead of true!-), and b as its instance, print 'x' in b will print True -- and so will any other containment check on b, since b always returns True (because self.d, a non-empty string, is true).

提交回复
热议问题