There should only be one and preferably only one obvious way to do it, says theZen 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.

So when should you use classes, and when should you use standard functions instead?
This story is a deeper dive into the matter.
For example, imagine youre writing a piece of code to organize the inventory of a clothes shop.

It’s free, every week, in your inbox.
Well add an option to add a price, too.
This code will run, but its not doing very much.

Try doing this implementation with standard functions, and youll probably have a lot more trouble dealing with it.
It basically means that you split up your program into different sections that deal with different pieces of information.
Classes, by their nature, allow you to keep to that principle.

Not only does this keep things neat and tidy; it is also a lot easier for maintenance.
This adds to the security of the code because youre less likely to use functions where they dont belong.
For example, you might have to build a method that is quite complex.

It is completely possible to build black-box-functions without using classes.
With classes, however, this key in of functioning is practically ensured.
When you define an instance of a class, that instance automatically inherits the given structure.

This makes the whole construct more flexible.
That is only valid, however, if you use multiple data structures in your code.
If your whole code wont ever deal with more than one structure.

If you only have one data structure, it really depends on the problem at hand.
Way easier than defining a new class!
Pythons inbuilt heapq, or heap queue algorithm,does the job for you.

In most cases, its a better idea to use functools.partial() instead.
Its quite simple to implement.
Say you have a function that multiplies two values, but you keep using it to double values.

But this is not a good habit!
The bottom line: Python classes are a two-edged sword
Classes are without doubt a powerful concept.
Used correctly, they can make your code tidier, more readable, and maintainable.

But they getoverused a lot.
And when used wrongly, they can pollute your code until you understand nothing.
As programs get more complex, the differences get more prominent.

It is, however, not always completely obvious.
The difficult part is recognizing which way is the good one.
This article was written byAri Jouryand was originally published onTowards Data Science.

Also tagged with
