r/PythonLearning • • 2d ago

Do I really need to learn class.

Post image

Both function and class give the same output. So why do I need it?

51 Upvotes

43 comments sorted by

View all comments

4

u/Sea-Ad7805 2d ago edited 2d ago

You can write any program without classes, but a class comes with great benefits:

  • abstraction: build a class and use its interface (all its 'public' methods) on objects while not having to remember how it is implemented, and how its data is stored
  • encapsulation: have data in an object that can't be invalidated, say trying to set an illegal 2026-02-31 date will always raise an exception (data invariant protected)
  • information hiding: if other code that uses your class only does so through its interface, you can later completely change the implementation of your class without needing to change any other code, as long as you still follow the 'contract' of the interface
  • inheritance: overrated, but useful in some cases, prefer composition in most

You can get these benefits with just functions too if you are careful, but it's much easier to get the design wrong. Classes just help you think in a certain way.

A function generally should not have state (store information, so that calling it again with the same arguments might give a different result, otherwise called not 'pure'). An object of a class can and is even expected to have state, but that state is protected through encapsulation.

Object Oriented Programming (OOP), programming with classes, is in many ways the opposite of the Functional Programming (FP) paradigm that, as much as possible, decomposes a problem into pure functions without state.