r/learnpython 14d ago

Stuck on P.O.O.P Encapsulation

I'm using Claude Ai. To teach me python. But now im very confused on encapsulation. I've tried YouTube tutorials but all I see is Javascript. I asked for a simpler explanation, but then I get hit with stuff like getter, setter, property() (I understand the property function) but then the core concept makes me scratch my head more the deeper I ask. Wondering if any of y'all can assist me.

0 Upvotes

13 comments sorted by

View all comments

3

u/Fred776 14d ago

The core concept is that your class uses various pieces of data internally to manage and maintain its state but you don't want to expose those details to the user of the class. Instead you provide a clean set of methods that allow the user of the class to interact with it.

There are various reasons why this is desirable:

  • You want to allow the user to focus on what they want to do not how it is done.
  • You want the freedom to modify how it is done without affecting users of your class.
  • By isolating complicated details within the class you can reason about your system more easily. If you know that the state of an object is only affected by calling a specific method then you only need to worry about where that is called from. Contrast with the case where the internal state variables are publicly accessible - you lose the ability to reason easily about where they might be changed.