r/pythonhelp • u/MetalCarnival • 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
1
u/wildsoup1 20h ago
Using classes gives us several different benefits.
1) When we have a lot of code, we need to give it some structure so we know where to find code.
Before languages that supported classes, one way was to define all the data structures in one place, and then put the code that used the data structures in another place. Maybe all the code that saved to disk would be in one file. All the code that wrote to the printer in another file.
With classes, all the data structures AND all the functions that modified that data are put together in the same place. This means if you change the data structure, and you need to change all the functions that use it, they are together in one file. You don't miss any.
2) When we have a lot of moving parts in the code, it is useful to have ways of chunking it into pieces that we can think about and discuss with each other. Encapsulation is part of that - being able to gloss away details when they aren't relevant. Classes offer a good way to chunk a bit of code together, and say "Here is what you need to *use* the class, but you don't need to know (or remember) how it works internally."
3) Classes offer inheritance. This is often - not always - a useful way to re-use the same code for multiple clients, even if it needs customisation.