8 Defining user-friendly classes

 

This chapter covers

  • Defining the initialization method
  • Creating instance, static, and class methods
  • Applying encapsulation to a class
  • Creating proper string representations
  • Defining a superclass and subclasses

The core of any application is data. Although built-in data types are useful for managing data, you’ll find them to be limited because they only have attributes and methods that are designed to address the most generic functionalities, including named tuples (section 3.3). You may have noticed that you don’t have useful methods to manipulate tasks with named tuples. But the task management app (like all applications in general) addresses specific business needs, which require data models that can handle those needs. Thus, custom classes are irreplaceable elements in your application. By defining proper attributes for the class, you can better capture the data needed in your application. By defining proper methods, you can better process the data in your application.

In this chapter, I focus on how to define attributes and different kinds of methods for your class, mostly using the Task class as part of the task management app to discuss the pertinent topics. The goal of defining a good custom class is to make it user-friendly—not only robust in terms of its attributes and methods (what should be available), but also maintainable in terms of implementing its functionalities in a clear organization (how they are structured).

8.1 How do I define the initialization method for a class?

8.1.1 Demystifying self: The first parameter in __init__

8.1.2 Setting proper arguments in __init__

8.1.3 Specifying all attributes in __init__

8.1.4 Defining class attributes outside the __init__ method

8.1.5 Discussion

8.1.6 Challenge

8.2 When do I define instance, static, and class methods?

8.2.1 Defining instance methods for manipulating individual instances

8.2.2 Defining static methods for utility functionalities

8.2.3 Defining class methods for accessing class-level attributes

8.2.4 Discussion

8.2.5 Challenge

8.3 How do I apply finer access control to a class?