Why to use classes instead of functions in python? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why to use classes instead of functions in python?

Hey everyone, I am a beginner in python and currently learning about the classes in python. I am finding it hard to learn how classes work in python! There are many things that confuses me like use of self everywhere but the thing I wanna know first is: Why to use classes if anything can be done without them? and When to use classes instead of using other approaches? (As sometimes using classes is complex than using others approaches)

15th Jan 2022, 3:38 AM
Sandeep
Sandeep - avatar
2 Answers
+ 3
Classes are mainly useful to structure larger programs into smaller bits which represent meaningful abstractions, and can potentially be reused. In Python, under the hood, classes are not that much different from functions, both are "objects" that have certain properties attached to them. But classes have special powers that they can implement magic methods, which allows us for example to write custom iterable data structures, override the meaning of operators between our own objects, and do other useful stuff. In smaller programs, using just functions can be perfectly fine and usual for Python.
15th Jan 2022, 4:12 AM
Tibor Santa
Tibor Santa - avatar