Extending Built-in Functions
Learn how can we add additional functionalities in our classes.
We'll cover the following
One interesting use of this kind of inheritance is adding functionality to built-in classes. In the Contact
class seen earlier, we are adding contacts to a list of all contacts. What if we also wanted to search that list by name? Well, we could add a method on the Contact
class to search it, but it feels like this method actually belongs to the list itself.
Example 1
The following example shows how we can do this using inheritance from a built-in type. In this case, we’re using the list
type. We’re going to inform mypy
that our list is only of instances of the Contact
class by using list["Contact"]
. For this syntax
to work in Python, we need to also import the annotations
module from the __future__
package. The definitions look like this:
Get hands-on with 1400+ tech skills courses.