Sobes.tech
Junior

How does attribute usage convention work in Python?

sobes.tech AI

Answer from AI

In Python, access to an object's attributes is governed by a convention based on name prefixes.

  1. Public attributes: Start without a prefix underscore. They are considered part of the class's public API and can be accessed and modified from outside.
  2. Protected attributes: Start with a single underscore (_). They are considered internal to the class or module. The convention suggests that such attributes should not be used directly from outside, although they are technically accessible.
    class MyClass:
        def __init__(self):
            self.public_attribute = "public"
            self._protected_attribute = "protected" 
    
    obj = MyClass()
    print(obj.public_attribute) # Access to public attribute
    print(obj._protected_attribute) # Access to protected attribute (not recommended from outside)
    
  3. Private attributes: Start with two underscores (__) and do not end with an underscore. Python performs "name mangling": __attribute is transformed into _ClassName__attribute. This makes direct access from outside more difficult, but not impossible.
    class AnotherClass:
        def __init__(self):
            self.__private_attribute = "private"
    
        def get_private(self):
            return self.__private_attribute
    
    obj2 = AnotherClass()
    # print(obj2.__private_attribute) # Will raise AttributeError
    print(obj2.get_private()) 
    print(obj2._AnotherClass__private_attribute) # Access via mangled name (not recommended)
    

This is a convention, not strict enforcement (except for name mangling). The developer is responsible for following these rules to ensure code readability and maintainability.

How does attribute usage convention work in Python… - sobes.tech