Language: EN

python-modificadores-acceso

Access Modifiers in Python

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

Python does not implement encapsulation in a “strict” manner 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("Luis")
print(person.greet())  # Output: Hello, I am Luis

Protected Access

Attributes and methods that start 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 start with two 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("María")
# print(student.__name)  # Error: AttributeError (cannot be accessed directly)
# student.__introduce()  # Error: AttributeError (cannot be called directly)

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

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