Operator overloading
Python's operators, +
, /
, -
, *
, and so on, are implemented by special methods on classes. We can apply Python operators more widely than the built-in numbers and collection types. Doing this can be called "overloading" the operators: letting them work with more than the built-in types.
Looking back at the The collections.abc module section, earlier in this chapter, we dropped a hint about how Python connects some built-in features with our classes. When we look at the collections.abc.Collection
class, it is the abstract base class for all Sized
, Iterable
, Containers
; it requires three methods that enable two built-in functions and one built-in operator:
- The
__len__()
method is used by the built-inlen()
function. - The
__iter__()
method is used by the built-initer()
function, which means it's used by thefor
statement. - The
__contains__()
method is used by the built-inin
operator. This operator is implemented by methods...