What does double underscore prefix do in Python variables?


When a double underscore is added as prefix to python variables the name mangling process is applied to a specific identifier(__var)

In order to avoid naming conflicts with the subclasses, name mangling includes rewriting the attribute name.

Example

Following is the program to explain the double underscore in Python −

class Python: def __init__(self): self.car = 5 self._buzz = 9 self.__fee = 2 d = Python() print(dir(d))

Output

Following is an output of the above code −

['_Python__fee', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_buzz', 'car']

Understanding the above code

  • The single underscore, double underscore, and normal elements are compared taking a class in the code above.

  • The basic keywords car, buzz, and fee are used here as placeholders for values that may change depending on input conditions or fresh data that the program has received.

  • Here, a list of the valid attributes of the object passed as an argument to the function is provided by the dir() function.

The car and _buzz variables appear to be unaffected in the code above, but the __fee variable has been changed to _Python__fee. In order to prevent the variable from being overwritten in subclasses, name tangling is performed on it in this manner.Double

Underscore (__) Prefix Variable in Python

In Python, private variables are defined with double underscore prefixes. This is also sometimes referred to as a "dunder." These names enforce the local scope of the variables they refer to. Python mangles a variable's name when it is declared in a function with a double underscore so that it cannot be outside of the scope.

Example

Following is an example of double underscore prefix variable in Python −

We'll make a class called Python as an example. A function-settable property called __name will be added to this class. Additionally, we'll create a way for the function to access the __name property.

class Sports: def __init__(self, players): self.players = players def names(self, names): self.__names = names def GetName(self): return self.__names Cricket = Sports(12) Cricket.names("Sachin Tendulkar") print(Cricket.GetName()) print(Cricket.players) print(Cricket.__names)

Output

When we access the Cricket Sports from inside the class, the code above gives it a name and writes out the name. You can see from the output below that while we can directly access players, we are unable to do so for the names.

Sachin Tendulkar12
Traceback (most recent call last):
   File "main.py", line 12, in <module>
print(Cricket.__names)AttributeError: 'Sports' object has no attribute '__names'

Example

To demonstrate how overriding functions, let's create a new class that inherits from Coding class.

class PythonClass(): def __init__(self): super().__init__() self.d = "overriding" self._e = "overriding" self.__f = "overriding" object2 = PythonClass() print(object2.d) print(object2._e) print(object2.__f)

Output

Following is an output of the above code −

overriding
overriding
Traceback (most recent call last):
  File "main.py", line 12, in 
print(object2.__f)AttributeError: 'PythonClass' object has no attribute '__f'

The name mangling again works here. The object2. f is changed to the _PythonClass__f. Now, put that element to print using modified Attribute.

print(object2._PythonClass__f)

Now, the output comes as follows −

overriding
overriding
overriding

Example

The following example determines that the class's methods can be used to access the Double Pre Underscore variables.

class Python: def __init__(self): self.__datacamp = "Programming" def get_datacamp(self): return self.__datacamp object = Python() # Printing the "Programming" that is a __var print(object.get_datacamp()) # An error occurs here. The name of the variable is changed print(object.__datacamp)

Output

Following is an output of the above code −

Programming
Traceback (most recent call last):
  File "main.py", line 11, in <module>
print(object.__datacamp)
AttributeError: 'Python' object has no attribute '__datacamp'

Example

Also, for the method names, you can use the double pre underscore.

class Python: def __getdatacamp(self): return "Programming" def calling_datacamp(self): return self.__getdatacamp() object = Python() # Returning the double underscore prefix method print(object.calling_datacamp()) # An error occurs here print(object.__getdatacamp())

Output

Following is an output of the above code −

Programming
Traceback (most recent call last):
  File "main.py", line 11, in 
    print(object.__getdatacamp())
AttributeError: 'Python' object has no attribute '__getdatacamp'

Example

Let's take another look at name mangling. We'll first make a variable called Python , and then we'll try to access it using the Doble Pre Underscore name.

_Python__name = "Programming" class Python: def return_name(self): return __name object = Python() # The __name variable gets printed print(object.return_name())

Output

Following is an output of the above code −

Programming

Updated on: 23-Nov-2022

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements