Essential type hints for class definitions
A class name is also a type hint, allowing a direct reference between a variable and the class that should define the objects associated with the variable. This relationship lets tools such as mypy
reason about our programs to be sure that object references and method references appear to match the type hints in our code.
We'll use type hints in three common places in a class definition:
- In method definitions, we'll use type hints to annotate the parameters and the return type.
- In the
__init__()
method, we may need to provide hints for the instance variables that define the state of the object. - Any attributes of the class overall. These are not common and type hints are rare here.
Getting ready
We're going to examine a class with a variety of type hints. In this example, our class will model a handful of dice. We'll allow rerolling selected dice, making the instance of the class...