The function of classes is to unite structure with demeanor in a logical way:
- Lists, dictionaries, tuples, etc describe a data structure. They may be more or less semantic, but they are sufficient to group common data. But the data itself does nothing, it just exists...
- Functions, procedures, arrangements, etc describe a functionality, I mean, something to be done, something that changes the internal state of the computer. They can receive data as input, return data as output, have side effects on other data, access streams... However, each function is an isolated procedure, decoupled from the individual data in which it operates (unless it is global data).
The classes unite both in a single concept - the object - that at the same time has data organized in a semantic way and also methods that act in these data in an organized way. This allows you to treat the class as a guy, such as the existing types in the language (a number can be summed, subtracted, multiplied, divided, a string can be concatenated, etc.; a class object C
can undergo operations X
, Y
and Z
).
And just as one class can define a type, another class can define a subtype (i.e. a more specific type, a subset so to speak), reusing the structure and functionality of the superclass (the most general type) and adding its own.
There are several other details in the class concept, some applicable to Python and others not (e.g. Python does not have encapsulation), but the fundamentals are these. It is perfectly possible to program without using classes [defined by you], and in some cases simpler is even recommended, in my opinion (like everything else, classes are tools, to be used when they are useful and left out when they are not). But knowing them and knowing when to use them will bring benefits, whether in clarity, concision, semantics, etc, will give you an extra resource to deal with the complexity inherent in computational systems.
Your question does not only involve python, it is the old stop programming Functional X OO
– Isvaldo Fernandes
@Isvaldofernandes The answer is good, but I think he wants an answer in practice, with examples showing "situations" and explaining. At least that’s what it looks like :)
– Guilherme Nascimento
I find one so easy to explain, Our world is not Linear/functional, We need to describe processes and use modeling to better represent our goals when we program, everything around us is full of features and actions, OO programming is the closest model to our reality.
– Isvaldo Fernandes
@Isvaldofernandes I remember this question elsewhere about PHP (same question why classes), the answer to principle would be something like: it’s hard to understand why use
class
when "functions solve", the truth is that theclass
can share a variable between various functions/methods within the class and deliver a specific result in another method and each called method can result in a different response, of course.– Guilherme Nascimento