-1

Often I check if a substring is present in a string. In Python I could do that either using the __contains__() method or using the in operator as shown below:

Pattern 1:

string1 = r'c:\users\username\documents\code\crime_data.csv'
print(string1.__contains__('username'))

Pattern 2:

print('username' in string1)

Both work well for me, but I would like to know why is __contains__ hidden method and if pattern 2 preferred over 1, if so why? Other programming languages like C# do have a String.contains() method in their standard library.

artemisart
  • 181
  • 1
  • 6
gDexter42
  • 117
  • 8
  • 2
    Why would you want to write `x.contains(y)` instead of `y in x`? The reason `__contains__` is a magic method is the same as the reason you write `x + y` and not `x.__add__(y)`, namely that, where an infix operator is available, it is generally more readable than a function call. – BrenBarn Feb 17 '17 at 19:53
  • 1
    When you call `something in something2` Python looks for a magic `__contains__` method in `something2` object and calls it (and for some builtins the interpreter can even optimize away such call). The `in` is just a syntactic sugar to keep the code more readable. As to why is it a separate method - so that you can create your own types that can be compared with other types. – zwer Feb 17 '17 at 19:54
  • Furthering what BrenBarn said, the `in` operator is also faster than a method call. – miradulo Feb 17 '17 at 19:54

1 Answers1

3

The in operator can be overloaded by redefining the method __contains__. This is no different from e.g. __add__ (+), __mul__ (*), etc. So the point is not to hide the method, but to make it fit the convention for 'magic methods', used to overload operators.

jonrsharpe
  • 99,167
  • 19
  • 183
  • 334
Jacques de Hooge
  • 6,204
  • 2
  • 19
  • 37