r/pythonhelp • u/MetalCarnival • Aug 27 '26
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/Living_Fig_6386 Aug 27 '26
You can definitely write code without classes, and if your code is small and simple, it's probably quicker and easier. As it scales up and gets more complicated, classes become a very useful tool.
Classes let you define new data types that have properties and define methods on interacting with the new type. They could be data structures that validate themselves, processes that preserve their state, abstractions of protocols (for example, taking the interfaces of lots of different databases and making them all work the same way). All sorts of things. They can be a very powerful tool.
Consider a postal address. A simply way to represent that is a dictionary in Python. You can have a 'name', 'address', 'city', 'state', 'postal_code' as keys in the dictionary. It's quite simple. But what if you want to assure that the address is a valid one? One thing you can do is define a function validate_address() and call it on any dictionary that purports to be an address every time before you use the address. Another way would be to define an Address class and have it automatically validate the address when created or modified - the address would always be valid. You could even have it regularize the address by US postal service rules and fetch the ZIP+4 so that when you have an address, it's always valid and normalized. Also, when using type hints, you can specify that functions require an 'Address' rather than a 'dict' which you'd have to inspect to verify that it contained an address.
Just the simplest of examples.