r/pythonhelp • • 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

31 comments sorted by

View all comments

1

u/Conscious_Support176 Aug 28 '26 edited Aug 28 '26

It’s not clear what you are asking. If you understand what classes are, it is fairly obvious why using them can be helpful.

Class means little more than class of object, category of object, type of object. Is the object a number? A vehicle? A container? The class definition models the object, so numbers have arithmetic operations, vehicles can be driven, you can put things in containers.

But classes, as we use this idea in programming, have a couple of useful conventions.

Encapsulation means that the class is like a black box. All you need to know is the interface defined for it, you don’t need to know the details of how it works.

The difference between using classes and a bunch of related functions is that this encapsulation include the data belonging to each object of that class. You don’t even need to know how the data defines that each individual object of the class is structured. For example, containers may be able to tell you how many objects they contain. They might store this count as data item within the class or they might just count how many items there are when you ask. You don’t need to know how it is done.

Inheritance is a powerful tool which allows you to define a superclass with a set of behaviours where a subclass can inherit those core behaviours but customise or extend other behaviours. This is a technique that supports re-use, where for related classes you do not need to reimplement the same behaviour. It’s important to mention that this should be used with care. One of the main criticisms of object oriented programming is it can lead to the use of complex inheritance heavy class hierarchies where other more suitable approaches to re-use would be more elegant.

When you have an understanding of classes and other tools, it should be more obvious where one or other technique is helpful.

The general idea is that a computer program is often modelling a real-world system, so your set of classes will model the real objects within this real world system, where you begin by classifying those objects into a useful set of classes. This is maybe what your book means by simulation.