InterviewSolution
| 1. |
Single and double underscore symbols have special significance in Python. When and where are they used? |
|
Answer» Python identifiers with leading and/or single and/or double underscore characters i.e. _ or __ are used for giving them a peculiar meaning. Unlike C++ or Java, Python doesn’t restrict access to instance attributes of a class. In C++ and Java, access is controlled by public, PRIVATE or protected keywords. These keywords or their equivalents are not defined in Python. All resources of class are public by default. However, Python does allow you to indicate that a variable is private by prefixing the name of the variable by double underscore __. In the following example, Student class has ‘name’ as private variable. >>> class Student: def __init__(self): self.__name='Amar'Here __name acts as a private attribute of object of Student class. If we try to access its value from outside the class, Python raises AttributeError. >>> x=Student() >>> x.__name TRACEBACK (most recent call last): File "<pyshell#37>", line 1, in <module> x.__name AttributeError: 'Student' object has no attribute '__name'However, Python doesn’t restrict access altogether. Python only internally renames such attribute in the form _classname__attribute. Here __name is RENAMED as _Student__name. The mechanism is called name mangling >>> x._Student__name 'Amar'An attribute with single underscore prefix emulates the behaviour of a protected data member INDICATING that it is available only to subclass. Python uses attributes and methods with double underscore CHARACTER before and after the name to form magic methods. Examples are __init__() and __dir__() etc. |
|