After this lesson you can stop other code from putting your objects into an invalid state, for example a bank balance below zero or a negative price.
The idea
Encapsulation means an object looks after its own data. Outsiders use a small, clear set of methods, and the object makes sure the data stays sensible. A shop's till does not let you set the total to "minus fifty" directly. You press buttons, and the till decides what is allowed.
Python is relaxed about this. It does not have private and public keywords. It relies on naming conventions and on programmers behaving sensibly.
Underscore conventions
A name that starts with one underscore means "internal: not part of the public interface". Python lets you use it anyway, but anyone who does is on their own:
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self._balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("deposit must be positive")
self._balance += amount
def balance(self):
return self._balance
acct = Account("Asha", 100)
acct.deposit(50)
print(acct.balance())
print(acct._balance)150
150The last line works, but it breaks the convention. Code outside the class should call balance().
Double underscore and name mangling
Two leading underscores trigger name mangling: Python quietly renames the attribute by adding the class name in front. It is designed to prevent accidental clashes between a class and its subclasses, not to hide data:
class Vault:
def __init__(self):
self.__secret = "blue door"
def reveal(self):
return self.__secret
vault = Vault()
print(vault.reveal())
print(vars(vault))blue door
{'_Vault__secret': 'blue door'}The attribute is stored as _Vault__secret. Anyone can still read it by that name, so do not treat it as security. For most code, a single underscore is enough.
Properties: validation without changing the syntax
Suppose you started with a plain price attribute and everyone writes item.price = 5. Later you want to reject negative prices. If you switch to set_price() methods, you must rewrite every caller. A property avoids this: the callers keep writing item.price, while your code runs behind the scenes.
class Item:
def __init__(self, name, price):
self.name = name
self.price = price
@property
def price(self):
return self._price
@price.setter
def price(self, value):
if value < 0:
raise ValueError("price cannot be negative")
self._price = value
pen = Item("Pen", 2.5)
pen.price = 3.0
print(pen.price)3.0Two methods share the name price. The one marked @property is run when you read it. The one marked @price.setter is run when you assign to it. The real value is kept in _price. Notice that __init__ assigns to self.price, not self._price, so even the first value is validated.
Invalid values now fail loudly:
pen.price = -1ValueError: price cannot be negativeRead-only and calculated properties
A property with no setter is read-only. This suits values that are worked out from other data:
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
@property
def area(self):
return self.width * self.height
box = Rectangle(3, 4)
print(box.area)
box.width = 10
print(box.area)12
40The area is always up to date because it is calculated whenever you ask. Trying to assign to it fails:
box.area = 99AttributeError: can't set attributeHow much is enough?
Do not wrap every attribute in a property. A plain attribute is simpler, and because properties keep the same syntax, you can change your mind later without breaking callers. Add a property when you need validation, a calculated value, or a read-only field.
A video version of this topic is in the video course at /learn/python/.
Common mistakes
- Using the same name for the property and the stored value. If the getter returns
self.priceand the value is also stored inself.price, the property calls itself forever. Store the value in_price. - Forgetting the
@price.setterline. The property becomes read-only and assignments fail. - Assigning to
self._pricein__init__. That skips validation for the first value. - Thinking double underscores are security. Mangled names are still reachable.
- Writing getters and setters for everything. Java habits are not needed in Python. Use plain attributes until you need more.
Exercise
Write a class Student with a property mark that only accepts numbers from 0 to 100 (raise ValueError otherwise). Create a student with mark 80, set the mark to 95 and print it, then try to set it to 120 inside a try block and print the error message.
Show one possible answer
class Student:
def __init__(self, name, mark):
self.name = name
self.mark = mark
@property
def mark(self):
return self._mark
@mark.setter
def mark(self, value):
if not 0 <= value <= 100:
raise ValueError("mark must be between 0 and 100")
self._mark = value
s = Student("Asha", 80)
s.mark = 95
print(s.mark)
try:
s.mark = 120
except ValueError as error:
print(error)95
mark must be between 0 and 100Key points
- Encapsulation means keeping an object's data behind a controlled interface so that it stays valid.
- A single leading underscore, as in _balance, tells other programmers 'internal, please do not touch'. Python does not enforce it.
- A double leading underscore triggers name mangling, which avoids accidental clashes in subclasses. It is not real security.
- @property turns a method into something you read like an attribute, and @name.setter lets you validate assignments.
- Start with plain attributes and switch to properties only when you need validation or a calculated value.