- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Private Variables in Python
In actual terms (practically), python doesn’t have anything called private member variable in Python. However, adding two underlines(__) at the beginning makes a variable or a method private is the convention used by most python code.
Let’s understand this concept through an example −
class myClass: __privateVar = 27; def __privMeth(self): print("I'm inside class myClass") def hello(self): print("Private Variable value: ",myClass.__privateVar) foo = myClass() foo.hello() foo.__privateMeth
In the above program, __privMeth is a private method and __privateVar is a private variable. Let’s see its output now −
Private Variable value: 27 Traceback (most recent call last): File "C:/Python/Python361/privateVar1.py", line 12, in <module> foo.__privateMeth AttributeError: 'myClass' object has no attribute '__privateMeth'
From the above output, we can see that outside the class “myClass”, you cannot access the private method as well as the private variable. However, inside the class (myClass) we can access the private variables. In the hello() method, the __privateVar variable can be accessed (as shown above: “Private Variable value: 27”).
So from the above example, we can understand that all the variables and the methods inside the class are public by the method. When we declare data member as private it means they are accessible only side the class and are inaccessible outside the class. The technique of making a variable or method private is called data mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with a leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.
Double underscore names are meant to avoid accidental overriding by a subclass instead.
- Private Variables in Python Program
- Private Variables in C#
- What are public and private variables in Python class?
- Does Python have “private” variables in classes?
- Private Variables in a Subroutine in Perl
- Are the private variables and private methods of a parent class inherited by the child class in Java?
- Can we declare the variables of a Java interface private and protected?
- Why subclass doesn't inherit the private instance variables of superclass in Java?
- Python Context Variables
- Python Environment Variables
- Scope of Variables in Python
- CGI Environment Variables in Python
- Private Methods in C#
- Private Keyword in Java
- Private Destructor in C++