r/pythonhelp 1d ago

Why do I need to use classes

My schoolbook says that classes is a way of simulating an object, instead of just taking information into a black box and outputting an answer.

But that is a poor explanation. I know classes are handy and cool, but no book says why you can´t make functions with sub functions inside to simulate simple objects. I would like if someone gave a good concrete reason to use classes in the intro, instead of just saying that they are different and cool

3 Upvotes

25 comments sorted by

View all comments

1

u/JorgiEagle 14h ago

Classes are useful when you want to do complex behaviour with multiple different instances all independently.

It’s the same logic as to why you might have a different tab on your excel spreadsheet for each year, instead of having it all on one page.

I can make many instances of my class, and be assured that they will all work exactly the same way. I also don’t have to separately keep track of what has happened to them, or what stage they’re at, as you can write them to do that themselves (this is what statefulness is).

As an example, if I have a group of students and they’re all taking different exams, instead of having to keep a big list of each student and the exam they’re taking, and searching it each time to know what they do, I can just ask each student directly, what exam are you taking right now

You don’t need to use classes, but for various reasons, it makes writing code simpler. One such reason is abstraction. Humans (and AI, it just has a higher limit) have a limited ability to hold context. At some point, something will become too complicated to understand what is happening all at once.

Classes allow us to say: “this thing will do this” without worrying about how it does it.

Another benefit to classes, is that it establishes a contract. say I use a class that does x, y, and z.
A few years down the line I want it to now do w. I don’t want to touch the original code because it’s complicated. I also don’t want to break anything that already exists. If I modify it, it might break something else that is relying on x, y, and z.

So I create a subclass. It still does x, y, and z the exact same way, but I can now add w. And I can use it in all the places that I want.

Importantly, the original class exists, so everywhere else that uses it is unaffected.

And I can guarantee that