Summary

We've looked at a number of basic special methods, which are essential features of any class that we design. These methods are already part of every class, but the defaults that we inherit from the object may not match our processing requirements.

We'll almost always need to override __repr__(), __str__(), and __format__(). The default implementations of these methods aren't very helpful at all.

We rarely need to override __bool__() unless we're writing our own collection. That's the subject of Chapter 7, Creating Containers and Collections.

We often need to override comparison and __hash__() methods. These definitions are suitable for simple immutable objects, but are not at all appropriate for mutable objects. We may not need to write all the comparison operators; we'll look at the @functools.total_ordering decorator in Chapter 9, Decorators and Mixins - Cross-Cutting Aspects.

The other two basic special method names, __new__() and __del__(), are for more specialized purposes. Using __new__() to extend an immutable class is the most common use case for this method function.

These basic special methods, along with __init__(), will appear in almost every class definition that we write. The rest of the special methods are for more specialized purposes; they fall into six discrete categories:

  • Attribute access: These special methods implement what we see as object.attribute in an expression, object.attribute on the left-hand side of an assignment, and object.attribute in a del statement.
  • Callables: A special method implements what we see as a function applied to arguments, much like the built-in len() function.
  • Collections: These special methods implement the numerous features of collections. This involves operations such as sequence[index], mapping[key], and set | set.
  • Numbers: These special methods provide the arithmetic operators and the comparison operators. We can use these methods to expand the domain of numbers that Python works with.
  • Contexts: There are two special methods that we'll use to implement a context manager that works with the with statement.
  • Iterators: There are special methods that define an iterator. This isn't essential, as generator functions handle this feature so elegantly. However, we'll look at how we can design our own iterators.

In the next chapter, we will address attributes, properties, and descriptors.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset