PGoCareerGoCareer prep tools
Home
LoginSign up
  • Java
  • Python
  • AI
  • React
  • Angular
  • PHP
  • Node.js
  • SQL
  • DSA
  • HTML
  • CSS
  • JS
  • Spring
  • ML
  • MongoDB

Python · Theory

Encapsulation in Python

← All stacks

Theory

59/268

Encapsulation in Python

Encapsulation keeps data with the methods that are allowed to change it. On a bank account, Main should call deposit(100), not poke a.balance = -9. You hide the field with _balance or __balance and expose deposit / get_balance. The object protects its own rules — amount must be > 0.

Dry-run: Account starts at 0. deposit(100) → 100. deposit(-50) ignored. get_balance() prints 100. __balance is not for Main to touch. That is encapsulation for a fresher — not a long OOP essay.

Encapsulation in Python — output — 100. deposit(-50) ignored. __balance is not for Main to poke.

Diagram
Account
    __balance
         │ only via
         ▼
    deposit() / get_balance()
Exam tip

__balance + deposit that rejects negatives.

Example

# Encapsulation
class Account:
    def __init__(self):
        self.__balance = 0
    def deposit(self, amt):
        if amt > 0:
            self.__balance += amt
    def get_balance(self):
        return self.__balance

a = Account()
a.deposit(100)
a.deposit(-50)
print(a.get_balance())

Encapsulation in Python — output: 100. deposit(-50) ignored. __balance is not for Main to poke.

Short notes

  • DefHide fields. Expose safe methods.
  • Ruledeposit / get, not a.balance = -9.
  • Remember__balance name mangling.

Questions

1

Explain Encapsulation as if you are teaching a junior — definition, then one tiny script.

2

What does the example print, and why?

3

What mistake do freshers make with Encapsulation?

Previous← Abstraction in PythonNextAccess Modifiers in Python →
P

GoCareerGo

Utilities · Preparation Hub · Resume · CV · Tools — one workspace.

Workspace

DashboardProfilePreparation HubResume builderCV builderCareer planning

PDF Tools

Merge PDFSplit PDFCompress PDFImage to PDFAll toolsJobs

Image & QR

Compress ImageResize ImageQR ScannerQR GeneratorBlogIT interview prep

Company

FAQFeedbackContactPrivacyTermsSitemap

© 2026 GoCareerGo. Keep moving forward.