Access Modifiers in Python

In Python, access modifiers control the visibility of class attributes and methods. Python provides three types of access modifiers:

  • Public: Accessible from anywhere.
  • Protected: Intended to be used within the class and its subclasses.
  • Private: Intended to be used only within the class.

Public Members

Public members are accessible from anywhere, inside or outside the class. In Python, all attributes and methods are public by default.

Example

Here, we define a class with a public attribute and a public method that can be accessed both inside and outside the class.

</>
Copy
class Car:
    def __init__(self, brand):
        self.brand = brand  # Public attribute
    
    def display(self):
        print(f"Car brand: {self.brand}")  # Public method

# Creating an object of Car class
car = Car("Toyota")

# Accessing public attribute and method
print(car.brand)  # Accessing directly
car.display()  # Calling the public method

Output:

Toyota
Car brand: Toyota

Since brand and display() are public, we can access them directly outside the class without any restriction.


Protected Members

Protected members are indicated with a single underscore (_) and should only be accessed within the class or its subclasses. Though Python does not enforce this restriction, it is a convention.

Example

We create a class with a protected attribute and show how it can still be accessed but should be treated as intended for internal use.

</>
Copy
class Person:
    def __init__(self, name, age):
        self.name = name  # Public attribute
        self._age = age  # Protected attribute

    def display_info(self):
        print(f"Name: {self.name}, Age: {self._age}")

# Creating an object
person = Person("Alice", 30)

# Accessing protected attribute (not recommended)
print(person._age)  # Works, but not recommended

# Accessing through a method
person.display_info()

Output:

30
Name: Alice, Age: 30

Even though _age is marked as protected, Python does not enforce this rule. However, it is a convention that indicates it should not be accessed directly outside the class.


Private Members

Private members are prefixed with a double underscore (__) and cannot be accessed directly from outside the class. This is useful for restricting access to sensitive data.

Example

We define a class with a private attribute and see how to access it using a method inside the class.

</>
Copy
class BankAccount:
    def __init__(self, account_number, balance):
        self.account_number = account_number  # Public attribute
        self.__balance = balance  # Private attribute

    def deposit(self, amount):
        self.__balance += amount
        print(f"Deposited: {amount}. New Balance: {self.__balance}")

    def get_balance(self):
        return self.__balance  # Accessing private attribute inside the class

# Creating an object
account = BankAccount("12345", 1000)

# Trying to access private attribute (will cause an error)
# print(account.__balance)  # AttributeError

# Accessing private attribute through a method
print("Current Balance:", account.get_balance())

# Depositing money
account.deposit(500)

Output:

Current Balance: 1000
Deposited: 500. New Balance: 1500

Attempting to access __balance directly results in an error. Instead, we use the get_balance() method, which allows controlled access to private attributes.


Accessing Private Members Using Name Mangling

Python uses name mangling to make private attributes slightly harder to access. It renames the attribute internally using the format _ClassName__attributeName, but it can still be accessed if needed.

Example

We use name mangling to access a private attribute outside the class.

</>
Copy
class Secret:
    def __init__(self):
        self.__hidden_value = 42  # Private attribute

# Creating an object
secret_obj = Secret()

# Accessing private attribute using name mangling
print("Accessing private attribute:", secret_obj._Secret__hidden_value)

Output:

Accessing private attribute: 42

Even though __hidden_value is private, we can access it using _Secret__hidden_value. However, this is not recommended in real-world applications.


Conclusion

Python does not enforce strict access control like some other languages, but access modifiers are useful for better code organization:

  • Public: Used for general access.
  • Protected: Used for class-internal and subclass usage.
  • Private: Used for sensitive data that should not be modified outside the class.