
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Does Python Have Private Variables in Classes?
In Python there are no private variables in classes. By default all the variables and methods are public. There is sometimes an emulation of private variables by using the double underscore __ prefix to the variable's names. This makes these variables not easily accessed outside of the class. This is achieved through name mangling.
In name mangling, we declare data/method with at least 2 leading and at most 1 trailing underscore.
The name mangling process helps to access the class variables from outside the class. The class variables can be accessed by adding _classname to it. The name mangling is closest to private, not exactly private. Following is the syntax to access the private variable ?
Object._Classname__Member
Name mangling process
With the help of the dir() method, we can see the name mangling process that is done to the class variable. The name mangling process was done by the interpreter. The dir() method is used by passing the class object, and it will return all valid attributes that belong to that object. This method makes the members of the class into name-mangling method
Example
In the following example, although the members of the class are privatized using name mangling, they can still be accessed using the mangled names -
class Student: def __init__(self,name,rollno,year,branch): self.__name=name self.__rollno=rollno self.__year=year self.__branch=branch def display(self): print(f'Name :{self.__name}\nRollno:{self.__rollno}\nYear:{self.__year}\nBranch:{self.__branch}') class Student1(Student): def __init__(self,name,rollno,year,branch): self.branch=branch Student.__init__(self,name,rollno,year) def Display(self): print("Name:",self.__name) Student.display(self) print(f"Branch:{self.branch}") x1=Student('John',297,4,'EEE') x1.display() print("Accessing private name using name mangling:", x1._Student__name)
Following is the output of the above code -
Name :John Rollno:297 Year:4 Branch:EEE Accessing private name using name mangling: John