⚡0 XP🔥0

Encapsulation, Properties & Dunder Methods

Lesson 28 of 33 ⏱ 5 min read ✎ 3 exercises ❓ 5-question quiz ▶ Runs Python

Protect object data with _protected and __private attributes, use @property getters/setters, write class and static methods, and customise objects with __str__, __repr__, __eq__, __len__ and more.

The four pillars of OOP#

Pillar Meaning Covered in
Encapsulation bundle data with methods; protect internal data this lesson
Abstraction hide complex details behind simple methods this & previous lesson
Inheritance reuse code from a parent class previous lesson
Polymorphism same interface, different behaviour previous lesson

Encapsulation#

Encapsulation means keeping an object's data safe inside it and allowing changes only through controlled methods. For example, a bank account's balance shouldn't be set to any random number from outside - it should change only through deposit() and withdraw(), which check the rules.

Public, protected, private#

Python doesn't have strict private like Java. It uses naming conventions:

Name Type Meaning
self.name public use freely
self._balance protected "internal - don't use from outside" (convention only)
self.__pin private name is mangled to _ClassName__pin - hard to access by accident
▶ Try it YourselfPython
Ctrl + Enter to run
हिंदी में समझें

Encapsulation = data को object के अंदर सुरक्षित रखना, और उसे सिर्फ तय तरीकों (methods) से बदलने देना।

जैसे ATM: आप सीधे मशीन खोलकर पैसे नहीं निकाल सकते - आपको PIN डालकर withdraw का बटन दबाना पड़ता है, और मशीन balance की जाँच करती है।

Python में:

  • _balance (एक underscore) = "कृपया बाहर से इसे न छुएँ" - यह सिर्फ एक इशारा है।
  • __pin (दो underscore) = नाम बदल दिया जाता है ताकि गलती से बाहर से access न हो।

Properties: controlled access with @property#

A property looks like a normal attribute from outside, but runs a method behind the scenes - perfect for validation and computed values:

▶ Try it YourselfPython
Ctrl + Enter to run

Class methods and static methods#

Type Decorator First parameter Use for
Instance method (none) self working with one object's data
Class method @classmethod cls alternative constructors, class-level data
Static method @staticmethod (none) utility functions related to the class
▶ Try it YourselfPython
Ctrl + Enter to run

Dunder (magic) methods#

Methods with double underscores, like __init__, let your objects work with Python's built-in syntax and functions.

str and repr#

▶ Try it YourselfPython
Ctrl + Enter to run

Without __str__, print(b) shows something unhelpful like <__main__.Book object at 0x7f...>.

Common dunder methods#

Method Makes this work Example
__init__ Obj(...) constructor
__str__ / __repr__ print(obj), repr(obj) display
__len__ len(obj) size
__eq__, __lt__, ... ==, <, >... compare, sort
__add__, __sub__, ... +, -... arithmetic
__contains__ x in obj membership
__getitem__ obj[i] indexing
__iter__ for x in obj looping
▶ Try it YourselfPython
Ctrl + Enter to run

Making objects sortable#

▶ Try it YourselfPython
Ctrl + Enter to run

dataclasses - less boilerplate#

For classes that mainly store data, @dataclass writes __init__, __repr__ and __eq__ for you:

▶ Try it YourselfPython
Ctrl + Enter to run

Summary#

  • Encapsulation protects data: _name (internal, by convention), __name (name-mangled).
  • @property creates attributes backed by getter/setter methods - great for validation.
  • @classmethod gets cls (alternative constructors); @staticmethod gets nothing.
  • Dunder methods (__str__, __len__, __eq__, __add__, __lt__...) make objects work with Python syntax.
  • @dataclass auto-generates boilerplate for data classes.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Temperature with validation

Create class Temperature with a property celsius. The setter must raise ValueError if the value is below -273.15. Add a read-only property fahrenheit = celsius × 9/5 + 32.

2

Money object

Create class Money(amount):

  • __str__ returns "Rs. <amount>" with 2 decimals, e.g. Rs. 150.00
  • __add__ adds two Money objects and returns a new Money
  • __eq__ compares amounts
3

Playlist length

Make Playlist work with len() and with in by adding __len__ and __contains__ methods (based on self.songs).

Quick Quiz

Q1.

What does a single leading underscore (e.g. self._balance) mean?

Q2.

What happens to self.__pin inside class Account?

Q3.

Which method controls what print(obj) shows?

Q4.

What does @property do?

Q5.

What is the first parameter of a @classmethod?