Structuring our data with a class
We will take the example of a contact list application to illustrate how to model our data using Python classes. Even though the user interface may offer lots of different functionalities, we will need to define what attributes represent our domain model—in our case, each individual contact.
Getting ready
Every contact will contain the following information:
- A first and last name, which must not be empty
- An email address, such as
[email protected]
- A phone number with the (123) 4567890 format
With this abstraction, we can start writing the code of our Contact
class.
How to do it...
First, we define a couple of utility functions that we will reuse to validate the fields that are mandatory or must follow a specific format:
def required(value, message): if not value: raise ValueError(message) return value def matches(value, regex, message): if value and not regex.match(value): raise ValueError(message) return value
Then, we define our...