Python Practice › OOP Programs › Program 16

Encapsulation with a private attribute

EasyOOP Programs · 16 of 48

Write a Python program that demonstrates encapsulation.

Advertisement
Output
1500
False

Approach

  1. Keep the balance in a “private” attribute and change it only through methods.

Solution

Python
class Account:    def __init__(self, balance):        self.__balance = balance     def deposit(self, amount):        if amount > 0:            self.__balance += amount     def balance(self):        return self.__balance a = Account(1000)a.deposit(500)a.deposit(-50)print(a.balance())print(hasattr(a, "__balance"))
Output
1500
False

Line by line

Line 3

Two leading underscores trigger name mangling, so the attribute is hard to reach from outside.

Line 6

The method validates input, so the balance can never be decreased by a negative deposit.

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs

Leave a Comment