A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/encapsulation-in-python/ below:

Encapsulation in Python - GeeksforGeeks

Encapsulation in Python

Last Updated : 12 Jul, 2025

In 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 process of hiding the internal state of an object and requiring all interactions to be performed through an object's methods. This approach:

Python achieves encapsulation through public, protected and private attributes.

Encapsulation Python How Encapsulation Works : 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 the account database. Instead, the bank provides you with methods (functions) like deposit and withdraw to modify your balance safely.

Public Members

Public members are accessible from anywhere, both inside and outside the class. These are the default members in Python.

Example:

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:

Note: The __init__ method is a constructor and runs as soon as an object of a class is instantiated.  

Protected members

Protected members are identified with a single underscore (_). They are meant to be accessed only within the class or its subclasses.

Example:

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:

Private members

Private members are identified with a double underscore (__) and cannot be accessed directly from outside the class. Python uses name mangling to make private members inaccessible by renaming them internally.

Note: Python's private and protected members can be accessed outside the class through python name mangling

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:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4