Object Oriented Programming Concepts
Object Oriented Programming Concepts
Encapsulation
Encapsulation is the mechanism of bundling the data (variables, attributes) and the methods (functions, procedures) into a single unit, often known as a class, and restricting direct access to some object components of the class.
It prevents accidental interference and misuse of the methods and data. Think of encapsulation as a protective barrier that prevents the data from being accessed and tampered with directly.
Some benefits of Encapsulation include:
- Control: The main benefit of encapsulation is the control it provides over the data. By encapsulating the data, you can change one part of the code without affecting other parts.
- Security: Data hiding provides an important layer of security. It keeps the data and the code safe from external interference and misuse.
- Simplicity: Encapsulation makes the code more understandable and maintainable by isolating its different parts.
How Does Encapsulation Work?
Access Modifiers: Encapsulation is implemented using access modifiers like
private
,protected
, andpublic
. These modifiers control the scope and visibility of the class's members.Access Modifier Scope of Access private - Accessible only within the same class. protected - Accessible within the same class and subclasses, including those in different packages. public - Accessible from any class. Getters and Setters: Methods known as getters and setters are used to access and update the value of a private variable.
Example
Imagine a BankAccount
class that represents a bank account.
class BankAccount:
def __init__(self, balance=0):
self.__balance = balance # Private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
return "Deposit Successful"
else:
return "Invalid Deposit Amount"
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
return "Withdrawal Successful"
else:
return "Insufficient Funds"
def get_balance(self):
return self.__balance
In this example:
- The
__balance
attribute is private, which means it cannot be accessed directly from outside the class. - The methods
deposit
,withdraw
, andget_balance
are public, providing controlled access to__balance
(Encapsulation). So direct access to_balance
is restricted (Data Hiding).