9 Using classes beyond the basics

 

This chapter covers

  • Creating enumerations
  • Eliminating boilerplate of a custom class
  • Processing JSON data
  • Creating lazy attributes
  • Refactoring a cumbersome class

Python is an object-oriented language at its core. The hallmark of an object-oriented language is using objects to preserve data and provide functionalities, which generally requires you to implement well-defined custom classes. In chapter 8, you learned the essential techniques for defining a class. But many other techniques can help us define more robust custom classes so that we can build a more maintainable codebase with well-defined data models.

Custom classes typically require implementation of several special methods, for example, including __init__ and __repr__. As you code more, you may find it tedious to write these methods, as they can be boilerplate. Did you know that you can use the dataclass decorator to remove boilerplate?

In this chapter, you’ll learn advanced techniques. Some of these techniques, such as creating enumerations, have a specific use case (when you need enumerations, for example, such as the task status in our task management application). Other techniques are more fundamental, such as refactoring a cumbersome class and creating lazy attributes, which you’ll find useful no matter what application you’re making. Please pay special attention to these project-agnostic techniques.

9.1 How do I create enumerations?

9.1.1 Avoiding a regular class for enumerations

9.1.2 Creating an enumeration class

9.1.3 Using enumerations

9.1.4 Defining methods for the enumeration class

9.1.5 Discussion

9.1.6 Challenge

9.2 How do I use data classes to eliminate boilerplate code?

9.2.1 Creating a data class using the dataclass decorator

9.2.2 Setting default values for the fields

9.2.3 Making data classes immutable

9.2.4 Creating a subclass of an existing data class

9.2.5 Discussion