In Python attributes are public by convention: there is no private. A leading underscore (_balance) warns that something is internal. When you need to control how an attribute is read or assigned, you use a property: from outside it looks like a normal attribute, but inside it runs code.
class Account:
def __init__(self, balance=0):
self.balance = balance # goes through the setter
@property
def balance(self): # getter: used like an attribute
return self._saldo
@balance.setter
def balance(self, value): # setter: validates before storing
if value < 0:
raise ValueError("the balance cannot be negative")
self._saldo = value
@property
def balance_in_cents(self): # computed property, without setter: read-only
return round(self._saldo * 100)
c = Account(10.5)
c.balance += 4.5
print(c.balance) # 15.0
print(c.balance_in_cents) # 1500
try:
c.balance = -1
except ValueError as e:
print(e) # the balance cannot be negative
try:
c.balance_in_cents = 5
except AttributeError:
print("read-only") # read-only
@propertydefines the getter;@name.setterdefines how it is assigned. Without a setter, the property is read-only.- Validate in the setter and call it from
__init__(self.balance = balance, notself._balance = balance) so that validation also applies when the object is created. - Derived data (area, perimeter, price with tax) is better as read-only properties than as stored attributes: they never get out of date.
- You can start with a public attribute and turn it into a property later without changing the code that uses it. That is why in Python you do not write getters and setters “just in case”.
You practice it in Temperature with properties and Rectangle with computed properties.