Help regarding OOP: when are classes preferable over functions?

I just finished the first stage of the Python Object Oriented Programming subject in the Computing Science course. While I think I have grasped how to do it, I still have a bit of trouble envisioning when it is preferable to use classes over merely using functions that do what you want your script to do. Both are done when you need to do something repeatedly, but other than that the reasoning for when to use each remained unclear. Could somebody please provide a concrete example of when using a class is objectively more efficient than calling a regular function to do something? It all still seems too abstract to me.

Thanks in advance!

The code might be a bit beyond what you’ve seen already, but take a look here:

Collections Source Code

That’s the source for the collections library of Python, which defines objects like the Ordered Dictionary. ordereddict was an object created to satisfy a requirement that dictionary objects remember the order their keys were added. (This is now standard behaviour of the regular dict object, as of Python 3.7.)

You can see how a class is used to create a new object - the ordereddict - and define how it behaves.

In a broader sense, a function is a single repeatable action - say, calculating a tip. A class is a collection of related functionality, comprising a single repeatable object.

Does that help any?

1 Like

It helps, yes. Can’t say that I’d know when using a class would be preferable over functions when coding something myself, still, however.

The example you provided is for something that will be used by others to write code, so a class would indeed make more sense. How about when something is coded for one’s own use only, though?

Classes allow you to group similar functionality (like an ordered dictionary), which is great

Which is also the problem, if you have small program, classes are very likely overkill

I started to appreciate when classes when i started working on larger projects. Take this forum for example (haven’t worked on this, but its a good example). See all the functionality? Topics, replies, likes, quotes and much more. Then classes really help to structure your code nicely

Classes are also needed to understand python, because data types are also classes. Which explains the:

string.isupper()

syntax. See how we call isuper as a method?

1 Like

Classes have attributes and methods. While it’s an oversimplification to say these are the same as variables and functions, they are somewhat analogous. (A purist might bristle at that.) The codecademy Python glossary may help.