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'

Discover more from HintsToday

Subscribe to get the latest posts sent to your email.

Pages ( 3 of 7 ): « Previous12 3 45 ... 7Next »

Discover more from HintsToday

Subscribe now to keep reading and get access to the full archive.

Continue reading