Sobes.tech
Junior — Middle

How are private variables and methods declared inside a class in Python?

sobes.tech AI

Answer from AI

In Python, there are no true private variables and methods like in some other languages, but there are conventions and mechanisms to indicate their privacy.

  1. A single underscore _var is a convention that the variable or method is intended for internal use (unofficial privacy).

  2. Double underscore __var leads to name mangling, meaning the variable's name inside the class is changed to make external access more difficult.

Example:

class MyClass:
    def __init__(self):
        self._internal_var = 1  # conditionally private
        self.__private_var = 2  # name will be changed

    def __private_method(self):
        print("This is a private method")

obj = MyClass()
print(obj._internal_var)       # accessible, but not recommended
# print(obj.__private_var)    # will cause an error
print(obj._MyClass__private_var)  # access via name mangling

Thus, double underscores help hide variables and methods from direct access, but they are not fully private.