Skip to main content

Access Modifiers in Python

 


Learning Sections          show

Access Modifiers in Python

Access modifiers in Python are used to define the accessibility of class members. They help in controlling the visibility and access of variables and methods. Python has three types of access modifiers:

  • Public
  • Protected
  • Private

1. Public Members

Members declared as public are accessible from anywhere, both inside and outside the class. By default, all members are public in Python.

Example:


class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person("Alice", 30)
print(person.name)  # Output: Alice
print(person.age)   # Output: 30
    

2. Protected Members

Members declared as protected are accessible within the class and its subclasses. To declare a member as protected, prefix its name with a single underscore _.

Example:


class Person:
    def __init__(self, name, age):
        self._name = name
        self._age = age

class Employee(Person):
    def __init__(self, name, age, salary):
        super().__init__(name, age)
        self._salary = salary

    def display(self):
        print(self._name)
        print(self._age)
        print(self._salary)

emp = Employee("Bob", 25, 50000)
emp.display()  
    # Output:
    # Bob
    # 25
    # 50000
    
    

3. Private Members

Members declared as private are accessible only within the class. To declare a member as private, prefix its name with a double underscore __.

Example:


class Person:
    def __init__(self, name, age):
        self.__name = name
        self.__age = age

    def display(self):
        print(self.__name)
        print(self.__age)

person = Person("Charlie", 35)
person.display()  
    # Output:
    # Charlie
    # 35
    
# Accessing private members directly will raise an AttributeError
print(person.__name)  # AttributeError: 'Person' object has no attribute '__name'
    

Access modifiers are an essential feature for encapsulation, which is a core principle of object-oriented programming. They help to protect the internal state of objects and prevent unintended interference and misuse.