Language: EN

python-modificadores-acceso

Access Modifiers in Python

Encapsulation in Python is a concept that refers to the restriction of direct access to some components of an object, with the goal of preventing accidental modifications and ensuring controlled use of its attributes and methods.

Python does not implement encapsulation in a “strict” way like other object-oriented languages. But it does provide mechanisms that allow managing the visibility and access to the members of a class.

To do this, Python uses naming conventions to indicate the accessibility of class members.

Public Access

Attributes and methods that do not start with an underscore (_) are considered public and can be accessed from outside the class.

class Person:
    def __init__(self, name):
        self.name = name  # Public attribute

    def greet(self):
        return f"Hello, I am {self.name}"  # Public method

# Using the Person class
person = Person("John")
print(person.greet())  # Output: Hello, I am John

Protected Access

Attributes and methods that begin with a single underscore (_) are considered protected and should not be accessed directly from outside the class.

class BankAccount:
    def __init__(self, balance):
        self._balance = balance  # Protected attribute

    def show_balance(self):
        return f"Available balance: {self._balance}"  # Protected method

# Using the BankAccount class
account = BankAccount(5000)
print(account.show_balance())  # Output: Available balance: 5000
print(account._balance)  # Protected access (not recommended but possible)

Private Access

Attributes and methods that begin with double underscores (__) are considered private and should not be accessed directly from outside the class.

class Student:
    def __init__(self, name):
        self.__name = name  # Private attribute

    def __introduce(self):
        return f"Hello! I am {self.__name}"  # Private method

# Using the Student class
student = Student("Maria")
# print(student.__name)  # Error: AttributeError (cannot be accessed directly)
# student.__introduce()  # Error: AttributeError (cannot be called directly)

However, we do not have strict encapsulation. There are ways to access fields and methods, even if they are marked as “private” with __.

That is, they are “fairly protected,” but not 100% protected. Although I also tell you that bypassing the protection is almost always a bad idea 😉.