Sub topic 1
Plain Attributes and Encapsulation
Prerequisites
Assume you know how to define classes, use __init__, create instance attributes, raise exceptions, and read basic decorator syntax.
Plain attributes and why direct access is the default
An instance attribute is data stored on one object. In Python, the usual approach is to assign it directly:
class User:
def __init__(self, name):
self.name = name
user = User("Mina")
user.name = "Noah"
print(user.name) # Noahuser.name is both readable and writable. Python does not require a getter method such as get_name() or a setter method such as set_name(). Direct access is simple, clear, and easy to inspect.
A class can later replace direct storage with a property without changing the public spelling user.name. This makes properties useful when access needs behavior such as validation or calculation.
What encapsulation means in Python
Encapsulation means keeping an object's data and the operations that manage that data together. It also means defining which parts of an object are part of its public interface.
Python uses conventions rather than strict access barriers. A convention tells programmers how an attribute should be used, but the language usually does not prevent access.
flowchart TD
A[Object data] --> B[Public interface]
B --> C[Other code reads or updates the object]
A --> D[Internal implementation]
D --> E[Conventions guide access]Single underscore: signaling internal use
A single leading underscore signals that a name is intended for internal use:
class Account:
def __init__(self, balance):
self._balance = balance
def deposit(self, amount):
self._balance += amount_balance is still accessible:
account = Account(100)
print(account._balance)The underscore communicates, “Code outside this class should generally not depend on this name.” It does not enforce privacy.
Double underscore and name mangling
A double leading underscore asks Python to rewrite the name using name mangling:
class Account:
def __init__(self):
self.__balance = 0
account = Account()
try:
print(account.__balance)
except AttributeError:
print("the original name is unavailable")Inside Account, __balance becomes _Account__balance. This reduces accidental name clashes in subclasses. It is not a security feature:
print(account._Account__balance) # 0Name mangling is mainly useful when a base class needs to protect an internal name from being accidentally overridden. Prefer a single underscore for ordinary internal attributes.
Exercise
Which convention should you usually use for an implementation-detail attribute that subclasses may reasonably need to inspect?
Show answer
Use one leading underscore, such as _balance. It signals internal use without name mangling.