Python Access Modifiers

Access modifiers decide who can use the variables and methods of a class. Languages like Java have keywords for this, but Python has no strict rules. Instead, Python uses naming conventions with underscores.

TypeHow to writeWho can use it
PublicnameEveryone
Protected_nameThe class and its child classes (by convention only)
Private__nameOnly inside the class (Python renames it)

Public members

A normal member is public. You can read and change it from outside the class.

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary      # public

e1 = Employee("Kiran", 10000)
print(e1.salary)

e1.salary = 20000
print(e1.salary)
Output of the above program is

10000
20000


Protected members

A single underscore at the start tells other developers, “this is for internal use, please do not touch it”. Python does not block access, but child classes are expected to use it.

class Employee:
    def __init__(self, name, salary):
        self._name = name         # protected
        self._salary = salary     # protected

class Manager(Employee):
    def show(self):
        print(self._name, self._salary)

m = Manager("Kiran", 50000)
m.show()
Output of the above program is

Kiran 50000


Private members

Two underscores at the start make a member private. Python changes its name internally to _ClassName__name. This is called name mangling, so the normal name does not work from outside.

class Employee:
    def __init__(self, name):
        self.name = name
        self.__id = 101           # private

e = Employee("Kiran")
print(e.__id)
Output of the above program is

AttributeError: 'Employee' object has no attribute '__id'

The value is still there under the changed name, so private in Python is a strong hint and not real security.

print(e._Employee__id)
Output of the above program is

101


Use methods to read and change private data

The usual way is to keep data private and give public methods to work with it. This also lets you add checks.

class Account:
    def __init__(self, balance):
        self.__balance = balance

    def get_balance(self):
        return self.__balance

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount

a = Account(500)
a.deposit(200)
print(a.get_balance())
Output of the above program is

700

Keeping data private and using methods to access it is called encapsulation. Read the overview in Python OOPS Introduction and the interview answer What are public, protected and private attributes?


Summary

  • Public: name. Protected: _name. Private: __name.
  • Python uses conventions, and only private names are changed (name mangling).
  • Use methods to give controlled access to private data.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.