How it works
Python marks intended privacy by naming convention rather than enforcement, so encapsulation is a contract between programmers.
Expose behavior through methods and treat underscore-prefixed names as internal.
Common error
Assuming a leading underscore prevents access. It signals intent only.
Worked example
Python
class Wallet:
def __init__(self):
self._balance = 0
def deposit(self, amount):
if amount > 0:
self._balance += amount
def balance(self):
return self._balance
w = Wallet()
w.deposit(8)
w.deposit(-2)
print(w.balance())Output
8Methods enforce the intended update rule. A leading underscore communicates non-public implementation by convention; it does not create an impenetrable access boundary.
Exercises
4.3.1 · Explain
Why is directly changing _balance weaker than using deposit for normal client code?
Show solution
It bypasses the method validation and couples the caller to internal representation. Respect the public interface even when the language permits direct access.
4.3.2 · Write code
Write a Celsius class with a method returning Fahrenheit, and show the result for 0 degrees Celsius.
Show solution
Use the conversion inside an instance method.
One valid solution
class Celsius:
def __init__(self, value):
self.value = value
def fahrenheit(self):
return self.value * 9 / 5 + 32
print(Celsius(0).fahrenheit())Expected output
32.0