OneCompiler

Encapsulation Implementation in Python

305

Click Link to View Encapsulation.png

class BankAccount():
  """Represents a bank account with encapsulation."""
  
  def __init__(self,balance=0):
    self.__balance = balance  # Private attribute

    
  def deposit(self,amount):
    """Deposits money into the account."""
    if amount>0:
      self.__balance += amount
      print("deposit succesfull , new balance is : ",self.__balance)
    else:
      print("invalid deposit amount")
        
  def withdraw(self,amount):
    """Withdraws money from the account."""
    if amount > 0  and  amount <= self.__balance:
      self.__balance -= amount
      print("withdraw succesfull, new balance is : ",self.__balance)
    else:
      print("insufficient funds or invalid deposit amount")
        
    
  def getBalance(self):
    """Returns the account balance."""
    return self.__balance
      
      
#Create a bank account object
my_account = BankAccount(1000)

#Deposit money
my_account.deposit(500)

#Withdraw money
my_account.withdraw(200)

#Try to withdraw more than available
my_account.withdraw(1500)

#Get the current balance
balance = my_account.get_balance()
print("Current balance:", balance)