Sub topic 5
Your first property: the getter
This chapter assumes you can define classes with __init__, you know that self.x = ... creates an instance attribute, and you have seen the @ decorator syntax. You should also know the single-underscore convention for internal names, which the previous chapter covered.
What a getter does
A getter is a method that Python runs whenever someone reads an attribute. The @property decorator turns a method into a getter. Callers then write obj.name, not obj.name().
class Employee:
def __init__(self, name, salary):
self._name = name
self._salary = salary
@property
def name(self):
return self._name
e = Employee("Ada", 5000)
print(e.name) # Ada
print(type(Employee.name)) # <class 'property'>The class stores the real value in _name. The property name is the public way to read it. Outside code sees an ordinary attribute, but the class now controls what happens on each read.
Why start with a getter
Suppose you first ship a class with a plain self.name attribute, and callers already use e.name. Later you want to compute or check the value on each read. If you rename the attribute to a method get_name(), every caller breaks.
A property avoids that. You rename the stored value to _name and add a property called name. The public syntax stays the same. This is why Python code usually starts with plain attributes and adds properties only when needed.
How lookup works
A property is an object stored on the class, not on the instance. When you read e.name, Python finds the name property on Employee and calls its getter with e as self. The instance's __dict__ holds only _name and _salary.
Common errors
Calling the property like a method fails, because e.name is already the returned string:
e = Employee("Ada", 5000)
try:
e.name()
except TypeError as exc:
print(exc) # 'str' object is not callableReading the property inside its own getter causes infinite recursion. The getter and the stored value need different names:
class Bad:
@property
def value(self):
return self.value # calls the getter again
try:
Bad().value
except RecursionError:
print("the getter called itself")Other mistakes to watch for:
- Forgetting to set
_namein__init__. Reading the property then raisesAttributeErrorfor_name, which can look confusing at first. - Putting the same name on the instance and the property. A property with only a getter blocks assignment to that name, so
self.name = namein__init__fails withAttributeError. Assign to_nameinstead. - Expecting privacy.
e._nameis still readable. The underscore is a signal, not a lock.
Checking your understanding
Exercise
A class defines @property def total(self): return self.total. What happens when you read obj.total, and how do you fix it?
Show answer
The getter calls itself, so Python raises RecursionError. Store the value under a different name, such as self._total set in __init__, and have the getter return self._total.
Exercise
You wrote class Item with a getter price that returns self._price. In __init__ you wrote self.price = price. What error do you get, and why?
Show answer
AttributeError. The price property has no setter, so assigning to self.price is rejected. Assign to self._price in __init__ instead.