What is the meaning of single and double underscore before an object name?

 

In Python, using a single or double underscore before an object name is a convention used to indicate the "privacy" or "access level" of that object. It's a way to communicate to other developers how an object should be treated, although Python doesn't enforce access control like some other languages do.

  1. Single Underscore _:
    • A single underscore before an object name is a convention to indicate that the object is intended to be "protected" or "private" within its containing module or class. It suggests to other developers that they should not access or modify this object directly, although there are no strict rules preventing them from doing so.

Example of using a single underscore:

python
class MyClass: def __init__(self): self._my_variable = 42 # _my_variable is a "protected" variable def my_method(self): print("This is a public method.") def _my_protected_method(self): print("This is a protected method.") # Usage obj = MyClass() print(obj._my_variable) # Accessing a "protected" variable (not recommended) obj._my_protected_method() # Calling a "protected" method (not recommended)
  1. Double Underscore __:
    • A double underscore before an object name invokes "name mangling," which means the name of the object will be changed in a way that makes it harder to create subclasses that accidentally override the private methods and attributes of a parent class. This is used to create a form of "private" members that are harder to access from outside the class.

Example of using a double underscore:

python
class MyClass: def __init__(self): self.__my_private_variable = 42 # __my_private_variable is "name-mangled" def my_method(self): print("This is a public method.") def __my_private_method(self): print("This is a private method.") # Usage obj = MyClass() print(obj.my_method()) # Accessing a public method print(obj.__my_private_variable) # This will raise an AttributeError obj.__my_private_method() # This will raise an AttributeError

Keep in mind that these conventions are not enforced by Python, and developers can still access these "protected" or "private" members if they choose to do so. However, it's considered good practice to respect these conventions and not access or modify "protected" or "private" members directly from outside the class or module to maintain code integrity and encapsulation.

Comments