Open In App

Access Modifiers in Python : Public, Private and Protected

Last Updated : 05 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisites: Underscore (_) in Python, Private Variables in Python

Encapsulation is one of the four principles used in Object Oriented Paradigm. It is used to bind and hide data to the class. Data hiding is also referred as Scoping and the accessibility of a method or a field of a class can be changed by the developer. The implementation of scoping is different for different programming language. For example, statically typed, compiled language has direct support to scoping with the help of keywords which are mentioned when the method or field is declared. However Python does not have such keywords since it is a scripting language, and it is interpreted instead of being compiled. Mainly, Access Modifiers can be categorized as Public, Protected and Private in a class.

Python uses the ‘_’ symbol to determine the access control for a specific data member or a member function of a class. Access specifiers in Python have an important role to play in securing data from unauthorized access and in preventing it from being exploited. But it is not like other languages like Java and C++ since Python uses the concept of Name Mangling for achieving data hiding.


A Class in Python has three types of access modifiers:

  • Public Access Modifier: Theoretically, public methods and fields can be accessed directly by any class.
  • Protected Access Modifier: Theoretically, protected methods and fields can be accessed within the same class it is declared and its subclass.
  • Private Access Modifier: Theoretically, private methods and fields can be only accessed within the same class it is declared.

We are mentioning “Theoretically” because python doesn’t follow the textbook definition of such specifications. Instead, it depends on the programmer/organization as well as a unique feature of python called as name mangling using which we can mimic the actual security provided by access modifiers.

Public Access Modifier:

The members of a class that are declared public are easily accessible from any part of the program. All data members and member functions of a class are public by default. 

Python
# program to illustrate public access modifier in a class


class Geek:

    # constructor
    def __init__(self, name, age):

        # public data members
        self.geekName = name
        self.geekAge = age

    # public member function
    def displayAge(self):

        # accessing public data member
        print("Age: ", self.geekAge)


# creating object of the class
obj = Geek("R2J", 20)

# finding all the fields and methods which are present inside obj
print("List of fields and methods inside obj:", dir(obj))

# accessing public data member
print("Name:", obj.geekName)

# calling public member function of the class
obj.displayAge()

Output

List of fields and methods inside obj: ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'displayAge', 'geekAge', 'geekName']
Name: R2J
Age: 20


We are using dir() function to list down all the member variables and functions of the Geeks object which can be accessed. We can clearly see geekName, geekAge, displayAge and other inbuilt methods such as __str__, __sizeof__, etc. In the above program, geekName and geekAge are supposed to be public data members and displayAge() method is a public member function of the class Geek. These data members of the class Geek can be accessed from anywhere in the program since they are present in the list returned by dir() as it is.

Protected Access Modifier:

The members of a class that are declared protected are only accessible within the class where it is declared and its subclass. To implement protected field or method, the developer follows a specific convention mostly by adding prefix to the variable or function name. Popularly, a single underscore “_” is used to describe a protected data member or method of the class. Note that the python interpreter does not treat it as protected data like other languages, it is only denoted for the programmers since they would be trying to access it using plain name instead of calling it using the respective prefix. For example,

Python
# program to illustrate protected access modifier in a class

# super class
class Student:

    # protected data members
    _name = None
    _roll = None
    _branch = None

    # constructor
    def __init__(self, name, roll, branch):
        self._name = name
        self._roll = roll
        self._branch = branch

    # protected member function
    def _displayRollAndBranch(self):

        # accessing protected data members
        print("Roll:", self._roll)
        print("Branch:", self._branch)

# derived class
class Geek(Student):

    # constructor
    def __init__(self, name, roll, branch):
        Student.__init__(self, name, roll, branch)

    # public member function
    def displayDetails(self):

              # accessing protected data members of super class
        print("Name:", self._name)

        # accessing protected member functions of super class
        self._displayRollAndBranch()


stu = Student("Alpha", 1234567, "Computer Science")
print(dir(stu))

# protected members and methods can be still accessed
print(stu._name)
stu._displayRollAndBranch()

# Throws error
# print(stu.name)
# stu.displayRollAndBranch()

# creating objects of the derived class
obj = Geek("R2J", 1706256, "Information Technology")
print("")
print(dir(obj))

# calling public member functions of the class
obj.displayDetails()

Output

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass_
_', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_branch', '_displayRollAndBranch', '_name', '_roll']
Alpha
Roll: 1234567
Branch: Computer Science

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_branch', '_displayRollAndBranch', '_name', '_roll', 'displayDetails']
Name: R2J
Roll: 1706256
Branch: Information Technology

In the above program, _name, _roll, and _branch are protected data members and _displayRollAndBranch() method is a protected method of the super class Student. The displayDetails() method is a public member function of the class Geek which is derived from the Student class, the displayDetails() method in Geek class accesses the protected data members of the Student class. 

However, we can still access protected members of Student class directly by specifying the correct name of field and method i.e. adding underscore before them since it was declared by that name. We can also see that these declared fields and methods can be called since they are present in the list returned by the dir() function. If we try to access the using plain names such as stu.name and stu.displayRollAndBranch(), we get error since they are not saved by that name. Underscores are mainly used since other characters like “$”, “-“, “&”, etc. cannot be present in variable or function name.

Private Access Modifier:

The members of a class that are declared private are accessible within the class only, private access modifier is the most secure access modifier. Data members of a class are declared private by adding a double underscore ‘__’ symbol before the data member of that class. 

Python
# program to illustrate private access modifier in a class

class Geek:

    # private members
    __name = None
    __roll = None
    __branch = None

    # constructor
    def __init__(self, name, roll, branch):
        self.__name = name
        self.__roll = roll
        self.__branch = branch

    # private member function
    def __displayDetails(self):

        # accessing private data members
        print("Name:", self.__name)
        print("Roll:", self.__roll)
        print("Branch:", self.__branch)

    # public member function
    def accessPrivateFunction(self):

        # accessing private member function
        self.__displayDetails()

# creating object
obj = Geek("R2J", 1706256, "Information Technology")

print(dir(obj))
print("")

# Throws error
# obj.__name
# obj.__roll
# obj.__branch
# obj.__displayDetails()

# To access private members of a class
print(obj._Geek__name)
print(obj._Geek__roll)
print(obj._Geek__branch)
obj._Geek__displayDetails()

print("")

# calling public member function of the class
obj.accessPrivateFunction()

Output

'_Geek__branch', '_Geek__displayDetails', '_Geek__name', '_Geek__roll', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'accessPrivateFunction']

R2J
1706256
Information Technology
Name: R2J
Roll: 1706256
Branch: Information Technology

Name: R2J
Roll: 1706256
Branch: Information Technology

In the above program, __name, __roll and __branch are private members, __displayDetails() method is a private member function (these can only be accessed within the class) and accessPrivateFunction() method is a public member function of the class Geek which can be accessed from anywhere within the program. The accessPrivateFunction() method accesses the private members of the class Geek.

However, we can still access private members of a class outside the class. We cannot directly call obj.__name, obj.__age, obj.__branch, and obj.__displayDetails() because they throw errors. We can notice that in the list of callable fields and methods, __name is saved as _Geek__name, __age is saved as _Geek__age, __branch is saved as _Geek__branch and __displayDetails() is saved as _Geek__displayDetails(). This conversion is called as name mangling, where the python interpreter automatically converts any member preceded with two underscores to _<class name>__<member name>. Hence, we can still call all the supposedly private data members of a class using the above convention.

Below is a program to illustrate the use of all the above three access modifiers (public, protected, and private) of a class in Python: 

Python
# program to illustrate access modifiers of a class

# super class
class Super:

    # public data member
    var1 = None

    # protected data member
    _var2 = None

    # private data member
    __var3 = None

    # constructor
    def __init__(self, var1, var2, var3):
        self.var1 = var1
        self._var2 = var2
        self.__var3 = var3

  # public member function
    def displayPublicMembers(self):

        # accessing public data members
        print("Public Data Member:", self.var1)

    # protected member function
    def _displayProtectedMembers(self):

        # accessing protected data members
        print("Protected Data Member:", self._var2)

    # private member function
    def __displayPrivateMembers(self):

        # accessing private data members
        print("Private Data Member:", self.__var3)

    # public member function
    def accessPrivateMembers(self):

        # accessing private member function
        self.__displayPrivateMembers()

# derived class
class Sub(Super):

      # constructor
    def __init__(self, var1, var2, var3):
        Super.__init__(self, var1, var2, var3)

      # public member function
    def accessProtectedMembers(self):

        # accessing protected member functions of super class
        self._displayProtectedMembers()

# creating objects of the derived class
obj = Sub("Geeks", 4, "Geeks!")

# calling public member functions of the class
obj.displayPublicMembers()
obj.accessProtectedMembers()
obj.accessPrivateMembers()
print()

# Can also be accessed using
obj._displayProtectedMembers()
obj._Super__displayPrivateMembers()
print()

# Object can access protected member
print("Object is accessing protected member:", obj._var2)
print("Object is accessing private member:", obj._Super__var3)

# object can not access private member, so it will generate Attribute error
# print(obj.__var3)

Output

Public Data Member: Geeks
Protected Data Member: 4
Private Data Member: Geeks!

Protected Data Member: 4
Private Data Member: Geeks!

Object is accessing protected member: 4
Object is accessing private member: Geeks!

In the above program, the accessProtectedMembers() method is a public member function of the class Sub accesses the _displayProtectedMembers() method which is protected member function of the class Super and the accessPrivateMembers() method is a public member function of the class Super which accesses the __displayPrivateMembers() method which is a private member function of the class Super. Also note that all these access modifiers are not strict like other languages such as C++, Java, C#, etc. since they can still be accessed if they are called by their original or mangled names.
 



Similar Reads

Should I Use "Public" Attributes or "Public" Properties in Python?
In Python, deciding whether to use "public" attributes or "public" properties can significantly impact the design and maintainability of your code. Public attributes are straightforward to use, while properties offer more control and encapsulation. Understanding the differences between these two approaches and knowing when to use each can help you
4 min read
Access Modifiers in Scala
Access Modifiers in scala are used to define the access field of members of packages, classes or objects in scala.For using an access modifier, you must include its keyword in the definition of members of package, class or object.These modifiers will restrict accesses to the members to specific regions of code. There are Three types of access modif
3 min read
Protected variable in Python
Prerequisites: Underscore ( _ ) in Python A Variable is an identifier that we assign to a memory location which is used to hold values in a computer program. Variables are named locations of storage in the program. Based on access specification, variables can be public, protected and private in a class. Protected variables are those data members of
2 min read
Create Password Protected Zip of a file using Python
ZIP is an archive file format that supports lossless data compression. By lossless compression, we mean that the compression algorithm allows the original data to be perfectly reconstructed from the compressed data. So, a ZIP file is a single file containing one or more compressed files, offering an ideal way to make large files smaller and keep re
2 min read
Read Modifiers in Wand Python
Read modifier refers to immediately modify input image or file format after reading or to make the image perfect to manipulate just after reading the image. This can be done by using the filename parameter of Image() function. For instance, let us say we want to read an image of (100 x 100) dimensions/aspect ratio but the original image is of (200
2 min read
How to download public YouTube captions in XML using Pytube in Python?
Prerequisite: Pytube Pytube is a dependency-free lightweight Python library for downloading YouTube videos. There are various APIs to fetch metadata from YouTube. In this article, we are going to see how to download public YouTube captions in XML using Python. Before starting we need to install this module: pip install pytube Approach: Import pytub
2 min read
Is __init__() a private method in Python?
Here in this article we are going to find out whether __init__() in Python is actually private or not. So we might come across many questions like What actually is __init__() method?What actually are private methods?And, if __init__() is private then how can we access it outside of a class? We have already heard about the concept that private metho
3 min read
Private Methods in Python
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP) in Python. It describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of data. A class is an example of encapsulation as i
6 min read
Private Variables in Python
Prerequisite: Underscore in PythonIn Python, there is no existence of “Private” instance variables that cannot be accessed except inside an object. However, a convention is being followed by most Python code and coders i.e., a name prefixed with an underscore, For e.g. _geek should be treated as a non-public part of the API or any Python code, whet
3 min read
Access metadata of various audio and video file formats using Python - tinytag library
Metadata extraction is a necessary task while making music players or other related applications. The best python library to read music metadata of various audio and video file formats is tinytag. This library allows you to access metadata of various audio and video file formats like mp3, m4a, mp4, flac, wav etc. The list of attributes you can acce
3 min read
Create and Access a Python Package
Packages are a way of structuring many packages and modules which helps in a well-organized hierarchy of data set, making the directories and modules easy to access. Just like there are different drives and folders in an OS to help us store files, similarly packages help us in storing other sub-packages and modules, so that it can be used by the us
5 min read
Python - Access Parent Class Attribute
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can
4 min read
How to access a collection in MongoDB using Python?
MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. MongoDB offers high speed, high availability, and high scalability. Accessing a Collection 1) Getting a list of collection: For getting a list of a MongoDB database's collections list_collection_names() method is used. This method returns
2 min read
Make Python API to access Mongo Atlas Database
Prerequisite: Python | Build a REST API using Flask RESTful APIs are a very helpful tool to manage the backend of an application. It can be used to define the architecture as well as manage the dependencies of the application using routes managed by the API. Flask is a popular micro framework for building web applications. In this article, we will
6 min read
Access object within another objects in Python
Prerequisite: Basics of OOPs in Python In this article, we will learn how to access object methods and attributes within other objects in Python. If we have two different classes and one of these defined another class on calling the constructor. Then, the method and attributes of another class can be accessed by first class objects ( i.e; objects w
2 min read
Access files of a devices in the same network using Python
We have so many ways to Transfer Files from one computer to another in Linux and Ubuntu but there we have to change the permissions of the Apache Folder and then Share the files. But in windows, we cannot share files using Apache so here we have discussed Python Method to Share files between Systems and Mobiles which are connected on the same netwo
2 min read
Access Index of Last Element in pandas DataFrame in Python
In this article, we are going to see how to access an index of the last element in the pandas Dataframe. To achieve this, we can use Dataframe.iloc, Dataframe.iget, and Dataframe.index. let's go through all of them one by one. Dataframe.iloc - Pandas Dataframe.iloc is used to retrieve data by specifying its index. In python negative index starts fr
3 min read
How to Access Index in Python's for Loop
In this article, we will discuss how to access an index in Python for loop in Python. Here, we will be using 4 different methods of accessing the Python index of a list using for loop, including approaches to finding indexes in Python for strings, lists, etc. Python programming language supports the different types of loops, the loops can be execut
3 min read
Install Python Modules without Root Access
Python is a popular programming language that gives users access to numerous modules. However, for the usage of those modules, the user needs to install those modules. The most common way of installing the Python modules is using the root access. While the most common way is using the root access, there are various other ways to install such module
3 min read
Access environment variable values in Python
An environment variable is a variable that is created by the Operating System. Environment variables are created in the form of Key-Value pairs. To Access environment variables in Python's we can use the OS module which provides a property called environ that contains environment variables in key-value pairs. In this article, we will see how to use
3 min read
Python | os.access() Method
os.access() method uses the real uid/gid to test for access to the path. Most operations use the effective uid/gid, therefore, this routine can be used in a suid/sgid environment to test if the invoking user has the specified access to the path. In this article, we will learn about the access() function of the OS module in Python. os.access() Funct
3 min read
How to access popup login window in selenium using Python
Many websites use sign-in using social media to make the login process easy for users. In most cases, if the button is clicked then a new popup window is opened where the user has to enter their user credentials. Manually one can switch windows in a browser and enter the required credentials to log in. But in case of unattended web access using a w
3 min read
How to Access dict Attribute in Python
In Python, A dictionary is a type of data structure that may be used to hold collections of key-value pairs. A dictionary's keys are connected with specific values, and you can access these values by using the keys. When working with dictionaries, accessing dictionary attributes is a basic function because it allows you to retrieve and modify the d
6 min read
Different ways to access Instance Variable in Python
Instance attributes are those attributes that are not shared by objects. Every object has its own copy of the instance attribute i.e. for every object, instance attribute is different. There are two ways to access the instance variable of class: Within the class by using self and object reference.Using getattr() method Example 1: Using Self and obj
2 min read
Handling Access Denied Error Occurs While Using Subprocess.Run in Python
In Python, the subprocess module is used to run new applications or programs through Python code by creating new processes. However, encountering an "Access Denied" error while using subprocess.run() can be problematic. This error arises due to insufficient permissions for the user or the Python script to execute the intended command. In this artic
5 min read
Access the Actual Tab Widget of ttk.Notebook in Python Tkinter
Tab widgets of ttk.Notebook are essential components in a Tkinter GUI for organizing content into multiple tabs. Accessing these tab widgets allows for customization and manipulation of their properties. In this article, we will explore two different approaches to accessing the actual tab widget of ttk.Notebook. Access the actual tab widget of ttk.
2 min read
Access a Site with Two-Factor Authentication Using Python Requests
web security is of paramount importance, and many websites implement two-factor authentication (2FA) to enhance security. This additional layer of security ensures that even if someone obtains your password, they cannot access your account without the second form of verification, usually a code sent to your phone or email. However, this added secur
4 min read
Why can't we access Python from a Conda Environment?
Conda environments are isolated spaces where we can install specific Python versions and packages without interfering with other projects. But sometimes, some issues may arise when trying to activate or use these environments. In this article, we will learn about accessing issues of Python from a conda environment. Problem Statement:You've created
2 min read
PyQt5 – Set and access description of push button
In this article we will see how to set and access the description of a push button. Description is basically the details about the push button i.e details refer to the text which describes about the push button. In order to set description we will use setAccessibleDescription method and to access the description we will use accessibleDescription me
2 min read
How to select last row and access PySpark dataframe by index ?
In this article, we will discuss how to select the last row and access pyspark dataframe by index. Creating dataframe for demonstration: C/C++ Code # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving an app name spark = SparkSession.builder.appNam
2 min read
Practice Tags :