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.
- 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.
- 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) - Private attributes: Start with two underscores (
__) and do not end with an underscore. Python performs "name mangling":__attributeis 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.