Encapsulation in python using public members
class Car:
def __init__(self, make, model):
self.make = make # Public member
self.model = model # Public member
def display_info(self):
print(f"Car make: {self.make}")
print(f"Car model: {self.model}")
# Creating an instance of the Car class
my_car = Car("Toyota", "Corolla")
# Accessing public members
print("Accessing public members:")
print("Make of the car:", my_car.make)
print("Model of the car:", my_car.model)
# Modifying public members
my_car.make = "Honda"
my_car.model = "Accord"
# Displaying modified information
print("\nModified information:")
my_car.display_info()
Encapsulation in python using private members
class BankAccount:
def __init__(self, account_number, balance):
self.__account_number = account_number # Private member
self.__balance = balance # Private member
def deposit(self, amount):
self.__balance += amount
def withdraw(self, amount):
if amount <= self.__balance:
self.__balance -= amount
else:
print("Insufficient funds")
def display_balance(self):
print(f"Account Balance: ${self.__balance}")
# Creating an instance of the BankAccount class
account = BankAccount("123456789", 1000)
# Accessing private members (will raise an AttributeError)
# print(account.__account_number)
# print(account.__balance)
# Accessing private members indirectly using public methods
account.display_balance()
# Depositing and withdrawing money
account.deposit(500)
account.withdraw(200)
# Displaying updated balance
account.display_balance()
Encapsulation in python using protected members
class Employee:
def __init__(self, name, salary):
self._name = name # Protected member
self._salary = salary # Protected member
def display_details(self):
print(f"Name: {self._name}")
print(f"Salary: ${self._salary}")
# Creating an instance of the Employee class
employee = Employee("John Doe", 50000)
# Accessing protected members (following the convention)
print("Accessing protected members:")
print("Employee name:", employee._name)
print("Employee salary:", employee._salary)
Python will warn you that you are using a protected attribute which you shouldnt
# Displaying details using a public method
employee.display_details()