Open In App

Private Attributes in a Python Class

Last Updated : 21 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Python, encapsulation is a key principle of object-oriented programming (OOP), allowing you to restrict access to certain attributes or methods within a class. Private attributes are one way to implement encapsulation by making variables accessible only within the class itself. In this article, we will explore how to create private attributes in a Python class.

Private Attributes in a Class in Python

Below are some of the examples by which we can understand about how we can create a private attribute in a class in Python:

Using Double Underscore Prefix

In this example, we have an id attribute of a class and we want to make the attribute private. So for making the attribute private, we can use (__).

Python3




# Creating a Class
class Student:
    name = "Lokesh Singh"
    __id = 1234 
     
    # Method for Printing Private Attribute
    def Print_Id(self):
        print(f"The Id of student is : {self.__id}")
     
lokesh = Student()
print(f"The name of student is : {lokesh.name}") # Public Attribute can be accessed directly from outside class
 
# Accessing private attribute using getter method
lokesh.Print_Id()


Output

The name of student is : Lokesh Singh
The Id of student is : 1234


Using Double Underscore Prefix with getter-setter method

In this example, we have defined a constructor that will set the data of student and a getter method to get the private data of the student as the private member cannot be accessed directly from outside the class.

Python3




class Student:
    def __init__(self, name, id):
        self.__id = id
        self.name = name
 
    def get_Id(self):
        return self.__id
 
# Setting the data of the student
sonali = Student("Sonali Kumari", 58)
 
# Printing the name as the name is public
print("The name is :", sonali.name)
 
# Printing the Id by getter method as the id is private
print("The id is :", sonali.get_Id())


Output

The name is : Sonali Kumari
The id is : 58


Using Property Decorator

In this example, we have used Property Decorator method to get the data. we have a constructor consisting of a private data and a method that will print the private data. As we know that private members of the class cannot be accesses outside the class.

Python3




class Private:
    def __init__(self):
        self.__private_attr = 10
 
    @property
    def Get_Private_Data(self):
        return self.__private_attr
 
obj = Private()
print("The Private Data is :", obj.Get_Private_Data)


Output

The Private Data is : 10




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads