When implementing __contains__() for a class, what is the proper return value to use?
Answer
The __contains__() method should always either return the values True or False to indicate whether the object “contains” the item being checked. How the class implements that check is dependent on the data contained in the class. However, the method should always return either True or False. If the method returns any other value, Python will try to convert or interpret the value as True or False and the resulting behavior may be unexpected.
Yes, I’ve got, thank you, but I was trying to answer to the second part of [pmgriego]'s (https://discuss.codecademy.com/u/pmgriego) question.( “Donelli” in d_and_p) did not work because of “wrong” quotes, as stetim94 has pointed; and I wrote about the possible reason why syntax (d_and_p.contains(“Donelli”)) did not work also. Can you tell please your expert opinion about the original question? It’s interesting…
There is no such attribute contains. The dunder method permits the use of the in keyword directly on the instance.
Consider,
>>> class Foo:
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
>>> a = Foo('faz', 'baz')
>>> 'foo' in a
Traceback (most recent call last):
File "<pyshell#134>", line 1, in <module>
'foo' in a
TypeError: argument of type 'Foo' is not iterable
>>>
Now,
>>> class Foo:
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
def __contains__(self, attr):
return attr in dir(self)
>>> a = Foo('faz', 'baz')
>>> 'foo' in a
True
>>>