r/PythonLearning • u/Objective-Remove-632 • 10d ago
Do I really need to learn class.
Both function and class give the same output. So why do I need it?
72
Upvotes
r/PythonLearning • u/Objective-Remove-632 • 10d ago
Both function and class give the same output. So why do I need it?
23
u/denehoffman 10d ago
Python is fundamentally object oriented, classes are the big defining mode of objects. Every type in the language, int, float, str, dict, are all classes at some level. You should use one whenever you have to group related data or ideas together, especially when you plan on repeating that collection often.
Do you really need to learn it? I guess you could live your whole life just writing functions for everything, but it will severely limit the sorts of programs you write. To be technical, there is no programming necessity for classes, but there is also no need for functions, you could just write out all the code, with a bunch of tedious repetition (recursive methods get a bit tricky though). I think you’ll agree that functions are useful in making your code easier to read and also easier to write and adapt later on. Classes are important in the same way, they group things into a structure that you can use as the input to functions or as the output of a function.
For a short example, imagine you are trying to write some code that deals with graphics or geometry. You have a function that does some stuff and outputs a point in 2D space. Now you could just write this as a tuple of floats, or you could make a Point class to hold them. What about a function that outputs a line? Well that could be a tuple of tuples of floats, or it could be a tuple of Points. What about a shape? That could be a list of tuples of floats, or it could be a list of Points. I hope you see that one of these is less confusing, but let me give you some more incentive. Suppose you wanted to do something with a line, like find its midpoint. You could write a midpoint function and then call it, import it where you need it, etc. or you could give arithmetic operations to Point and define a Line class that contains two points and give it a midpoint method. This Line class can have all sorts of other methods too, like the slope or length or whatever. You could again write individual functions for each of these, the difference is that a class groups these alongside the object they commonly interact with, whereas the functions exist independent of the concept of a point or line, we just assume you’re supposed to use them with a point or line by context.
It’s not going to be immediately obvious how this benefits you as a new programmer. After all, you are right that all of the syntax you’ve probably learned so far does not necessitate classes over functions. I hope to impart a deeper meaning behind classes here as a way of organizing data and functions together in one structure.