web analytics

Technology

How to get the most out of Python classes

todayJuly 31, 2021 2

Background
share close

There should only be one — and preferably only one — obvious way to do it”, says the Zen of Python. Yet there are areas where even seasoned programmers debate what the right or wrong way to do things is.

One of these areas is Python classes. Borrowed from Object-Oriented Programming, they’re quite beautiful constructs that you can expand and modify as you code.

The big problem is that classes can make your code more complicated than necessary, and make it harder to read and maintain. So when should you use classes, and when should you use standard functions instead?

This story is a deeper dive into the matter. So if you’re in a hurry, you can skip the following two sections and scroll right down to the sections When to use classes and When classes are a bad idea.

Python classes: the very basics

Classes are objects that allow you to group data structures and procedures in one place. For example, imagine you’re writing a piece of code to organize the inventory of a clothes shop.

You could create a class that takes each item of clothing in the shop, and stores key quantities such as the type of clothing, and its color and size. We’ll add an option to add a price, too.

Now, we can define various instances of the class and keep them organized:

We would add these two lines without indent, after the definition of the class. This code will run, but it’s not doing very much. We can add a method to set the price directly underneath the __init__ function, within the class definition:

We could also add some routines to tell us the price, or to promote an item by reducing the price:

Now, we can add some calls of our methods after the lines where we’ve initialized the instances of the class:

If you need to add more routines, you can just put them in the class definition.

The nicest part of all of this is that you can add and delete as many objects as you like. Deleting an attribute goes like so:

And if you want to delete an entire object, you do like so:

All of this is neat, simple, and expandable. Try doing this implementation with standard functions, and you’ll probably have a lot more trouble dealing with it.

From a theoretical point of view, there are more reasons why Python classes are a beautiful concept in many situations.

0%