Classes and Objects in Python- Object Oriented Programming & A Project

by lochan2014 | Jul 10, 2024 | Python | 0 comments

Encapsulation

Encapsulation is the bundling of data (attributes) and methods that operate on the data into a single unit (class), and restricting access to some of the object’s components. This is achieved using private and protected attributes.

Example of Encapsulation

class BankAccount:
    def __init__(self, account_holder, balance):
        self.account_holder = account_holder
        self.__balance = balance  # Private attribute

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount

    def withdraw(self, amount):
        if amount > 0 and amount <= self.__balance:
            self.__balance -= amount

    def get_balance(self):
        return self.__balance

account = BankAccount("John Doe", 1000)
account.deposit(500)
account.withdraw(200)

print(account.get_balance())  # Output: 1300
# print(account.__balance)  # AttributeError: 'BankAccount' object has no attribute '__balance'

Written By

undefined

Related Posts

Spark SQL- operators Cheatsheet- Explanation with Usecases

Spark SQL Operators Cheatsheet 1. Arithmetic Operators OperatorSyntaxDescriptionExample+a + bAdds two valuesSELECT 5 + 3;-a – bSubtracts one value from anotherSELECT 5 – 3;*a * bMultiplies two valuesSELECT 5 * 3;/a / bDivides one value by anotherSELECT 6 / 2;%a %…

Read More

Submit a Comment

Your email address will not be published. Required fields are marked *