public, private and protected access modifiers in Python

In programming languages like Java, C++, etc., private, protected and public keywords are used to control the access of class members. But in Python, there are no such keywords. By prefixing the name of variables and methods with a single or double underscore, you can make them protected and private members of a class respectively.

In Python, by default, all members of a class are public which means you can access them from outside the class without any restrictions.

Python public variables and methods

Public variables and methods are the least restricted members of a class.

#Python program to create public variables and methods of a class
class Person:
  def __init__(self, firstName, lastName):
    self.firstName = firstName
    self.lastName = lastName

  def display(self):
    print('My name is ', self.firstName, self.lastName)

p = Person("Mitali", "Natani")
print('First name: ', p.firstName)
print('Last name: ', p.lastName)
p.display()

Output of the above program

First name:  Mitali
Last name:  Natani
My name is  Mitali Natani

Python protected variables and methods

By prefixing variables and methods with a single underscore(_), you can make them protected members. Even after declaring like this, you can still access protected members and Python interpreter will not give any error.

#Python program to create protected variables and methods of a class
class Person:
  def __init__(self, firstName, lastName):
    self._firstName = firstName
    self._lastName = lastName

  def _display(self):
    print('My name is ', self._firstName, self._lastName)

p = Person("Mitali", "Natani")
print('First name: ', p._firstName)
print('Last name: ', p._lastName)
p._display()

Output of the above program

First name:  Mitali
Last name:  Natani
My name is  Mitali Natani

As you can see, we can access protected members of a class but as a good programmer, you must avoid doing this.

Python protected variables and methods

Private variables and methods are created by prefixing their name with double underscore. For more details and example on private members of a class, click here.