ENCAPSULATION
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). It describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of data. To prevent accidental change, an object’s variable can only be changed by an object’s method. Those types of variables are known as private variables.
Encapsulation also helps in achieving modularity and code maintainability. Since the internal implementation details are hidden, changes to the internal representation of an object can be made without affecting the code that uses the object. This allows for easier updates and modifications to the codebase, as the external code only relies on the public interface of the object.
In many programming languages, encapsulation is implemented using access modifiers such as public, private, and protected. These modifiers control the visibility and accessibility of class members (variables and methods). Private members are only accessible within the class itself, while public members can be accessed from any code that has a reference to the object.
A class is an example of encapsulation as it encapsulates all the data that is member functions, variables, etc. The goal of information hiding is to ensure that an object’s state is always valid by controlling access to attributes that are hidden from the outside world.
Note: The __init__ method is a constructor and runs as soon as an object of a class is instantiated.
Example :-
class bank_account:
def __init__(self):
self.balance = 0
self.name = ''
def welcome(self):
self.name = input('Welcome to your Bank Account. Please Enter your name : ')
# #balance check
def get_balance(self):
print('Your Current balance : {}'.format(self.balance))
#deposit amount
def deposit(self):
self.balance += float(input('Hello {}, please enter amount to deposit : '.format(self.name)))
self.get_balance()
##withdraw amount
def withdraw(self):
amount_to_withdraw = float(input('Enter amount to withdraw : '))
if amount_to_withdraw > self.balance:
print('You Have Insufficient Balance !!')
else:
self.balance -= amount_to_withdraw
self.get_balance()
if __name__=="__main__":
bank_account = bank_account()
bank_account.welcome()
while True:
input_value = int(input('Enter 1 to see your balance,\n2 to deposit \n3 to withdraw\n'))
if input_value == 1:
bank_account.get_balance()
elif input_value == 2:
bank_account.deposit()
elif input_value == 3:
bank_account.withdraw()
else:
print('Please enter a valid input.')
OUTPUT :-

