Encapsulation

Python · Functions & OOP

Theory

Encapsulation means bundling data and the methods that work on it inside one class, and controlling how outside code reaches that data. Python has no strict private keyword; it uses naming conventions instead. A single underscore, self._balance, signals 'internal, please do not touch' but is still accessible. A double underscore, self.__balance, triggers name mangling: Python renames it to _Account__balance, so a.__balance from outside raises AttributeError.

The usual pattern is to keep the raw data internal and expose safe methods such as get_balance() or deposit(amount) that can validate input (reject negative deposits) before changing state. The @property decorator lets you offer method-backed access with simple attribute syntax, like a.balance.

Why we use it

It protects an object's internal state from accidental or invalid changes, so the object is always in a valid condition. Callers depend on a stable set of methods, so you can change the internals later without breaking them.

When to use it

Use it for data with rules, such as balances that must not go negative or salaries that need validation. For simple data holders with no rules, plain public attributes are fine and very Pythonic.

How it works

  1. Outside code wants to change the balance
  2. Via a public method like deposit()? Yes: Validate the amount. No: a.__balance fails (mangled).
  3. Is the amount valid (> 0)? Yes: Update self.__balance. No: Raise ValueError.
  4. Object stays in a valid state

Syntax

class C:
    def __init__(self):
        self._protected = 1
        self.__private = 2

Example

class Account:
    def __init__(self, balance):
        self.__balance = balance
    def get_balance(self):
        return self.__balance

a = Account(500)
print(a.get_balance())

Key points

Python topics

Getting Started

Variables & Data Types

Operators

Strings

Lists

Tuples

Sets

Dictionaries

Control Flow

Loops

Functions & OOP

Working with Data

Tooling & Errors

File Handling

Exception Handling

NumPy Library

Pandas Basics

Data Cleaning

Combining DataFrames (SQL Joins & Unions)

GroupBy & SQL-Style Analytics

Reshaping & Workflow

Data Visualization

Machine Learning (Scikit-Learn)

Advanced Python & AI

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Python for Data Analysts

From basics to business insights — the complete step-by-step Python roadmap. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice Python Online 141 Python questions for data analysts — strings, records, dates, statistics and regex — with hidden tests and instant verdicts. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Python  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs real Python 3.12 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic