Sobes.tech
Junior — Middle

What are the access levels to data in Python and how are they declared?

sobes.tech AI

Answer from AI

In Python, data access levels are implemented through naming conventions for class attributes and methods, since the language does not have a strict access modifier system like Java or C++.

  • Public access: attributes and methods without underscores, e.g., variable. Accessible everywhere.
  • Protected access: attributes and methods with a single leading underscore, e.g., _variable. This is a convention indicating that such members are intended for use within the class and its subclasses.
  • Private access: attributes and methods with double leading underscores, e.g., __variable. Python applies name mangling, which changes the attribute's name to make external access more difficult.

Example:

class MyClass:
    public_var = 1
    _protected_var = 2
    __private_var = 3

obj = MyClass()
print(obj.public_var)       # 1
print(obj._protected_var)   # 2 (recommended not to use outside the class)
# print(obj.__private_var)  # AttributeError error
print(obj._MyClass__private_var)  # 3 (access via name mangling)