Visibility and encapsulation
suggest changeEncapsulation is the object-oriented principle of bundling data attributes and the methods that operate on them into a single unit, while restricting direct external access to internal implementation details. Unlike languages such as Java, C++, or C#, Python does not enforce access restrictions (public, protected, private) at the compiler level. Instead, Python relies on naming conventions, name mangling, and property descriptors, guided by the guiding community principle: "We are all consenting adults here."
1. Public Attributes
By default, every attribute and method defined on a Python class or instance is public. Any external caller or subclass can inspect, call, or modify it directly:
class Point:
def __init__(self, x: float, y: float):
self.x = x # Public attribute
self.y = y # Public attribute
def move(self, dx: float, dy: float) -> None:
self.x += dx
self.y += dy
p = Point(10.0, 20.0)
print(p.x) # Access public attribute
p.x = 15.0 # Modify public attribute directly
In Python, exposing public attributes directly is idiomatic when no validation or transformation logic is required.
2. Protected Attributes (Single Leading Underscore _)
Prefixing an attribute or method with a single underscore (e.g., _attribute) signifies that it is intended for internal use only by the class and its subclasses:
class DatabaseConnection:
def __init__(self, uri: str):
self.uri = uri
self._pool = [] # Protected: internal implementation detail
self._is_connected = False
def _establish_connection(self): # Protected helper method
print(f"Connecting to {self.uri}...")
self._is_connected = True
def query(self, sql: str):
if not self._is_connected:
self._establish_connection()
return f"Executing {sql}"
Key Characteristics
- Advisory Only: Python does not physically prevent access to
_poolfrom outside the class (conn._poolworks without runtime error). - Tooling Support: Static analysis tools (Mypy, Pylint, IDE autocomplete) flag direct access to
_prefixed members outside the class hierarchy as warnings. - Module Imports: When using
from module import *, identifiers starting with a single underscore_are excluded from being imported into the global namespace.
3. Private Attributes and Name Mangling (Double Leading Underscore __)
When an attribute or method name begins with two or more leading underscores (and at most one trailing underscore), Python triggers name mangling:
class BankAccount:
def __init__(self, initial_deposit: float):
self.__balance = initial_deposit # Private attribute
def deposit(self, amount: float) -> None:
if amount <= 0:
raise ValueError("Deposit must be positive")
self.__balance += amount
def get_balance(self) -> float:
return self.__balance
Attempting to access __balance directly from outside the class raises an AttributeError:
account = BankAccount(100.0)
account.deposit(50.0)
try:
print(account.__balance)
except AttributeError as e:
print(f"Caught error: {e}")
# Output: Caught error: 'BankAccount' object has no attribute '__balance'
How Name Mangling Works
Python automatically prefixes the attribute name with an underscore and the class name: _ClassName__attributeName. The attribute is still accessible using its mangled name:
# The mangled attribute still exists on the instance:
print(account._BankAccount__balance) # Output: 150.0
Purpose of Name Mangling
Name mangling is not a cryptographic security boundary; its primary goal is to prevent accidental name collisions in subclasses:
class BaseService:
def __init__(self):
self.__config = {"env": "prod"}
class DerivedService(BaseService):
def __init__(self):
super().__init__()
# Without mangling, this would overwrite the parent's config:
self.__config = {"local": True}
service = DerivedService()
# Both attributes safely coexist under their mangled names:
# service._BaseService__config
# service._DerivedService__config
Note: Methods with both double leading and double trailing underscores (e.g.,
__init__,__str__,__len__) are dunder methods (special magic methods) and are not mangled.
4. Encapsulation with @property Decorators
In languages like Java, developers are advised to write explicit getters and setters for every field (getAge(), setAge()). In Python, start with public attributes. When validation, transformation, or read-only access is needed later, use @property without breaking the public interface:
class TemperatureSensor:
def __init__(self, celsius: float):
self.celsius = celsius # Uses the setter below
@property
def celsius(self) -> float:
"""Getter for celsius."""
return self._celsius
@celsius.setter
def celsius(self, value: float) -> None:
"""Setter with validation."""
if value < -273.15:
raise ValueError("Temperature below absolute zero is impossible!")
self._celsius = float(value)
@property
def fahrenheit(self) -> float:
"""Derived read-only property."""
return (self._celsius * 9 / 5) + 32
Usage remains clean and idiomatic without explicit method calls:
sensor = TemperatureSensor(25.0)
print(sensor.celsius) # 25.0 (Calls getter)
print(sensor.fahrenheit) # 77.0 (Calls derived getter)
sensor.celsius = 30.0 # Calls setter with validation
print(sensor.fahrenheit) # 86.0
try:
sensor.celsius = -300.0 # Raises ValueError
except ValueError as e:
print(f"Validation failed: {e}")
try:
sensor.fahrenheit = 100.0 # Raises AttributeError (read-only)
except AttributeError as e:
print(f"Cannot set read-only attribute: {e}")
Summary of Conventions
| Style | Pattern | Meaning | Example |
|---|---|---|---|
| Public | name |
Freely accessible; stable public API | self.username |
| Protected | _name |
Internal convention; avoid external modification | self._cache |
| Private | __name |
Name mangled by interpreter (_Class__name); prevents collision in subclasses |
self.__secret_key |
| Special / Dunder | __name__ |
Reserved magic methods/attributes; never invent your own | def __repr__(self): |
| Trailing underscore | name_ |
Used by convention to avoid collision with Python keywords | class_, id_ |