chapter eight

8 Defining user-friendly classes

 

This chapter covers

  • Properly 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 in 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 that we introduced in section 3.3) — we don't have useful methods to manipulate tasks with named tuples. However, our task management app, or any applications in general, address specific business needs, which require data models that can handle these 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, we focus on how to define attributes and different kinds of methods for your class, mostly using the Task class as part of our 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 their 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?

8.3.1 Creating protected methods by using an underscore as the prefix

8.3.2 Creating private methods by using double underscores as the prefix

8.3.3 Creating read-only attributes with the property decorator

8.3.4 Verifying data integrity with a property setter

8.3.5 Discussion

8.3.6 Challenge