Chapter 8

What are classes? When should we use them?

Classes represent a way in which we can create complex objects, with the corresponding data (attributes) and functions (methods). Classes are a useful concept to represent any entity, such as a database connection, file object, algorithm, and so on. There's also a set of special methods and variables that's used by Python to change the behavior of certain instances.

Can we compare two instances of a class or use arithmetic operations with them?

Yes—this is one of the use cases for special methods. For example, in order for us to check instances for equality, we need to set the __eq__ method of the class. Here, we are checking whether the instance is greater, smaller, and so on—there is a corresponding special method for each operation.

When should we use inheritance?

Inheritance is an important property of classes. By inheriting from another class, you let your class acquire all the methods and attributes of the class you're acquiring from. If there is an overlap in the names, the values of your class are preserved. Inheritance is useful to avoid repetition; for example, if multiple classes have shared attributes or methods, it makes sense for all of them to inherit from the base class. Another frequent case for inheritance is to use a base class with some non-trivial behavior, for example, that's provided by an external framework, and override special attributes and methods that will be executed.

What is the use case for data classes?

Data classes are merely syntactic sugar—they simplify the code that's required to create a class and provide some properties, such as equality, initialization, and hashing, by default. They are extremely useful if your class is mostly required to store data.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.248.159