Private Attributes in a Python Class
Last Updated :
21 Feb, 2024
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
class Student:
name = "Lokesh Singh"
__id = 1234
def Print_Id( self ):
print (f "The Id of student is : {self.__id}" )
lokesh = Student()
print (f "The name of student is : {lokesh.name}" )
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
sonali = Student( "Sonali Kumari" , 58 )
print ( "The name is :" , sonali.name)
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
Share your thoughts in the comments
Please Login to comment...