Encapsulation means hiding internal details of a class and only exposing what’s necessary. It helps to protect important data from being changed directly and keeps the code secure and organized.
Technically, encapsulation is an object-oriented programming principle where data (variables) and methods (functions) are bundled together in a class.
EncapsulationWhy do we need Encapsulation?
- Protects data from unauthorized access and accidental modification.
- Controls data updates using getter/setter methods with validation.
- Enhances modularity by hiding internal implementation details.
- Simplifies maintenance through centralized data handling logic.
- Reflects real-world scenarios like restricting direct access to a bank account balance.
Example of Encapsulation
Encapsulation in Python is like having a bank account system where your account balance (data) is kept private. You can't directly change your balance by accessing account database. Instead, bank provides you with methods (functions) like deposit and withdraw to modify your balance safely.
- Private Data (Balance): Your balance is stored securely. Direct access from outside is not allowed, ensuring data is protected from unauthorized changes.
- Public Methods (Deposit and Withdraw): These are the only ways to modify your balance. They check if your requests (like withdrawing money) follow the rules (e.g., you have enough balance) before allowing changes.
Access Specifiers in Python
Access specifiers define how class members (variables and methods) can be accessed from outside the class. They help in implementing encapsulation by controlling the visibility of data. There are three types of access specifiers:
Types of Access ModifiersLet's discuss it one by one.
Public Members
Public members are variables or methods that can be accessed from anywhere inside the class, outside the class or from other modules. By default, all members in Python are public.
They are defined without any underscore prefix (e.g., self.name).
Example:
This example shows how a public attribute (name) and a public method (display_name) can be accessed from outside the class using an object.
Python
class Public:
def __init__(self):
self.name = "John" # Public attribute
def display_name(self):
print(self.name) # Public method
obj = Public()
obj.display_name() # Accessible
print(obj.name) # Accessible
Explanation:
- Public Attribute (name): This attribute is declared without any underscore prefixes. It is accessible from anywhere, both inside and outside of the class.
- Public Method (display_name): This method is also accessible from any part of the code. It directly accesses the public attribute and prints its value.
- Object (obj): An instance of Public is created, and the display_name method is called, demonstrating how public attributes and methods can be accessed directly.
Note: __init__ method is a constructor and runs as soon as an object of a class is instantiated.
Protected members
Protected members are variables or methods that are intended to be accessed only within the class and its subclasses. They are not strictly private but should be treated as internal.
In Python, protected members are defined with a single underscore prefix (e.g., self._name).
Example:
This example shows how a protected attribute (_age) can be accessed within a subclass, demonstrating that protected members are meant for use within the class and its subclasses.
Python
class Protected:
def __init__(self):
self._age = 30 # Protected attribute
class Subclass(Protected):
def display_age(self):
print(self._age) # Accessible in subclass
obj = Subclass()
obj.display_age()
Explanation:
- Protected Attribute (_age): Prefixed with a single underscore to indicate it’s protected. This is a convention in Python, not enforced it suggests limited access.
- Subclass Access: subclass inherits from Protected and can access _age directly.
- Method (display_age): Demonstrates that protected members are accessible within the class and its subclasses.
Private members
Private members are variables or methods that cannot be accessed directly from outside the class. They are used to restrict access and protect internal data.
In Python, private members are defined with a double underscore prefix (e.g., self.__salary). Python applies name mangling by internally renaming them (e.g., __salary becomes _ClassName__salary) to prevent direct access.
Example:
This example shows how a private attribute (__salary) is accessed within the class using a public method, demonstrating that private members cannot be accessed directly from outside the class.
Python
class Private:
def __init__(self):
self.__salary = 50000 # Private attribute
def salary(self):
return self.__salary # Access through public method
obj = Private()
print(obj.salary()) # Works
#print(obj.__salary) # Raises AttributeError
Explanation:
- Private Attribute (__salary): Defined with double underscores to make it private. Python uses name mangling to restrict direct access.
- Method (salary): A public method that safely returns the private attribute’s value.
- Direct Access: Attempting obj.__salary raises an AttributeError, showing that private members can't be accessed directly.
Declaring Protected and Private Methods
In Python, you can control method access levels using naming conventions:
- Use a single underscore (_) before a method name to indicate it is protected meant to be used within class or its subclasses.
- Use a double underscore (__) to define a private method accessible only within class due to name mangling.
Note: Unlike other programming languages, Python does not enforce access modifiers like public, private or protected at the language level. However, it follows naming conventions and uses a technique called name mangling to support encapsulation.
Example:
This example demonstrates how a protected method (_show_balance) and a private method (__update_balance) are used to control access. The private method updates balance internally, while protected method displays it. Both are accessed via a public method (deposit), showing how Python uses naming conventions for encapsulation.
Python
class BankAccount:
def __init__(self):
self.balance = 1000
def _show_balance(self):
print(f"Balance: ₹{self.balance}") # Protected method
def __update_balance(self, amount):
self.balance += amount # Private method
def deposit(self, amount):
if amount > 0:
self.__update_balance(amount) # Accessing private method internally
self._show_balance() # Accessing protected method
else:
print("Invalid deposit amount!")
account = BankAccount()
account._show_balance() # Works, but should be treated as internal
# account.__update_balance(500) # Error: private method
account.deposit(500) # Uses both methods internally
OutputBalance: ₹1000
Balance: ₹1500
Explanation:
- _show_balance(): (Protected method) Accessible from outside, but intended for internal or subclass use.
- __update_balance(): (Private method) Only accessible inside class due to name mangling.
- deposit(): Public method that safely uses both private and protected methods.
Getter and Setter Methods
In Python, getter and setter methods are used to access and modify private attributes safely. Instead of accessing private data directly, these methods provide controlled access, allowing you to:
- Read data using a getter method.
- Update data using a setter method with optional validation or restrictions.
Example:
This example shows how to use a getter and a setter method to safely access and update a private attribute (__salary).
Python
class Employee:
def __init__(self):
self.__salary = 50000 # Private attribute
def get_salary(self): # Getter method
return self.__salary
def set_salary(self, amount): # Setter method
if amount > 0:
self.__salary = amount
else:
print("Invalid salary amount!")
emp = Employee()
print(emp.get_salary()) # Access salary using getter
emp.set_salary(60000) # Update salary using setter
print(emp.get_salary())
Explanation:
- __salary is a private attribute, so it can't be accessed directly from outside the class.
- get_salary() is a getter method that safely returns the current salary.
- set_salary(amount) is a setter method that updates the salary only if the amount is positive.
- The object emp uses these methods to access and modify the salary while keeping the data protected.
Similar Reads
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. OOPs is a way of organizing code that uses objects and classes to represent real-world entities and their behavior. In OOPs, object has attributes thing th
11 min read
Python Classes and Objects In Python, classes and objects are the core of object-oriented programming. A class defines the structure and behavior of objects, while objects are instances of these classes. Understanding how to create and use classes is essential for writing clean, maintainable code. In this article, weâll cover
9 min read
Python objects A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to
2 min read
Class and Object
self in Python classIn Python, self is a fundamental concept when working with object-oriented programming (OOP). It represents the instance of the class being used. Whenever we create an object from a class, self refers to the current object instance. It is essential for accessing attributes and methods within the cla
6 min read
Class and Instance Attributes in PythonClass attributes: Class attributes belong to the class itself they will be shared by all the instances. Such attributes are defined in the class body parts usually at the top, for legibility. Python # Write Python code here class sampleclass: count = 0 # class attribute def increase(self): samplecla
2 min read
Create a Python SubclassIn Python, a subclass is a class that inherits attributes and methods from another class, known as the superclass or parent class. When you create a subclass, it can reuse and extend the functionality of the superclass. This allows you to create specialized versions of existing classes without havin
3 min read
Inner Class in PythonPython is an Object-Oriented Programming Language, everything in Python is related to objects, methods, and properties. A class is a user-defined blueprint or a prototype, which we can use to create the objects of a class. The class is defined by using the class keyword.Example of classPython# creat
5 min read
Python MetaClassesThe key concept of python is objects. Almost everything in python is an object, which includes functions and as well as classes. As a result, functions and classes can be passed as arguments, can exist as an instance, and so on. Above all, the concept of objects let the classes in generating other c
9 min read
Creating Instance Objects in PythonIn Python, an instance object is an individual object created from a class, which serves as a blueprint defining the attributes (data) and methods (functions) for the object. When we create an object from a class, it is referred to as an instance. Each instance has its own unique data but shares the
3 min read
Dynamic Attributes in PythonDynamic attributes in Python are terminologies for attributes that are defined at runtime, after creating the objects or instances. In Python we call all functions, methods also as an object. So you can define a dynamic instance attribute for nearly anything in Python. Consider the below example for
2 min read
Constructors in PythonIn Python, a constructor is a special method that is called automatically when an object is created from a class. Its main role is to initialize the object by setting up its attributes or state. The method __new__ is the constructor that creates a new instance of the class while __init__ is the init
3 min read
Why Python Uses 'Self' as Default ArgumentIn Python, when defining methods within a class, the first parameter is always self. The parameter self is a convention not a keyword and it plays a key role in Pythonâs object-oriented structure.Example:Pythonclass Car: def __init__(self, brand, model): self.brand = brand # Set instance attribute s
3 min read
Encapsulation and Access Modifiers
Encapsulation in PythonIn Python, encapsulation refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit, typically a class. It also restricts direct access to some components, which helps protect the integrity of the data and ensures proper usage.Encapsulation is the
6 min read
Access Modifiers in Python : Public, Private and ProtectedPrerequisites: Underscore (_) in Python, Private Variables in PythonEncapsulation is one of the four principles used in Object Oriented Paradigm. It is used to bind and hide data to the class. Data hiding is also referred as Scoping and the accessibility of a method or a field of a class can be chan
9 min read
Access Modifiers in Python : Public, Private and ProtectedPrerequisites: Underscore (_) in Python, Private Variables in PythonEncapsulation is one of the four principles used in Object Oriented Paradigm. It is used to bind and hide data to the class. Data hiding is also referred as Scoping and the accessibility of a method or a field of a class can be chan
9 min read
Private Variables in PythonPrerequisite: Underscore in PythonIn Python, there is no existence of âPrivateâ instance variables that cannot be accessed except inside an object. However, a convention is being followed by most Python code and coders i.e., a name prefixed with an underscore, For e.g. _geek should be treated as a n
3 min read
Private Methods in PythonEncapsulation is one of the fundamental concepts in object-oriented programming (OOP) in Python. 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
6 min read
Protected variable in PythonPrerequisites: Underscore ( _ ) in Python A Variable is an identifier that we assign to a memory location which is used to hold values in a computer program. Variables are named locations of storage in the program. Based on access specification, variables can be public, protected and private in a cl
2 min read
Inheritance
Inheritance in PythonInheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (called a child or derived class) to inherit attributes and methods from another class (called a parent or base class). In this article, we'll explore inheritance in Python.Why do we need Inheritance in Pyt
7 min read
Method Overriding in PythonMethod overriding is an ability of any object-oriented programming language that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, the same parameter
7 min read
Operator Overloading in PythonOperator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because '+' operator is overloaded by int class and str class. You might have noticed t
8 min read
Python super()In Python, the super() function is used to refer to the parent class or superclass. It allows you to call methods defined in the superclass from the subclass, enabling you to extend and customize the functionality inherited from the parent class.Syntax of super() in PythonSyntax: super()Return : Ret
8 min read
Multiple Inheritance in PythonInheritance is the mechanism to achieve the re-usability of code as one class(child class) can derive the properties of another class(parent class). It also provides transitivity ie. if class C inherits from P then all the sub-classes of C would also inherit from P. Multiple Inheritance When a class
5 min read
What Is Hybrid Inheritance In Python?Inheritance is a fundamental concept in object-oriented programming (OOP) where a class can inherit attributes and methods from another class. Hybrid inheritance is a combination of more than one type of inheritance. In this article, we will learn about hybrid inheritance in Python. Hybrid Inheritan
3 min read
Multilevel Inheritance in PythonPython is one of the most popular and widely used Programming Languages. Python is an Object Oriented Programming language which means it has features like Inheritance, Encapsulation, Polymorphism, and Abstraction. In this article, we are going to learn about Multilevel Inheritance in Python. Pre-Re
3 min read
Multilevel Inheritance in PythonPython is one of the most popular and widely used Programming Languages. Python is an Object Oriented Programming language which means it has features like Inheritance, Encapsulation, Polymorphism, and Abstraction. In this article, we are going to learn about Multilevel Inheritance in Python. Pre-Re
3 min read
Polymorphism
Abstraction
Special Methods and Testing
Additional Resources