Here is my code:
class a(object):
d='ddd'
def __contains__(self):
if self.d:return True
b=a()
print b.contains('d') # error
print contains(b,'d') # error
See also: Override Python's 'in' operator? for the corresponding how-to implementation question.
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 isin— the “containment check” operator.With your class
aas you present it (except for fixing your typo, and usingTrueinstead oftrue!-), andbas its instance,print 'x' in bwill printTrue— and so will any other containment check onb, sincebalways returnsTrue(becauseself.d, a non-empty string, is true).