Basic Data Classes
The colon (
:) notation used for the fields is a feature that was introduced in Python 3.6 called variable annotations. You’ll soon see more about this notation and why we specify data types like
str (string) and
float. Those few lines of code are all you need.
Later in the course, you’ll learn about
default_factory, which gives a way to provide more complicated default values. So far, we have not made a big fuss of the fact that data classes support typing out of the box.
You’ve probably noticed that we defined a field with a type hint:
name: str says that
name should be a text string. In fact, adding some kind of type hint is mandatory when defining the fields in your data class. Without a type hint, the field will not be a part of the data class.
04:16 You already know that a data class is just a regular class. This means you can freely add any methods you want to that class. As an example, let us calculate the distance between one position and another along the Earth’s surface. One way to do this is by using the haversine formula, which is seen onscreen.
Become a Member to join the conversation.