Computer >> Computer tutorials >  >> Programming >> Python

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 −

privateVar1.py

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 −

Output

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.