Sub topic 14
Overriding properties in subclasses
This chapter assumes you can write a property with a getter and a setter, and that you know basic inheritance and super(). It covers what happens when a subclass defines or changes a property that a parent class already has. A few rules are unintuitive, and some of the mistakes fail silently.
A property is a class attribute
@property creates an object and stores it in the class namespace under the attribute's name. It is an ordinary class attribute that happens to be a descriptor. The chapter on descriptors covers the mechanism in detail. Here you only need two facts:
- A property lives on the class that defines it, not on instances.
- A
propertyobject bundles up to three functions:fget,fset, andfdel.
When you read obj.balance, Python searches the classes in type(obj).__mro__ in order and uses the first one that has balance in its namespace. If that attribute is a property, Python calls its fget.
The consequence is that the first class in the MRO that defines balance wins, and it wins as a whole property. The subclass's property does not merge with the parent's. It replaces it.
The base class used in this chapter
All examples below build on this class.
class Account:
def __init__(self, balance):
self.balance = balance # runs the setter
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
if value < 0:
raise ValueError("balance cannot be negative")
self._balance = valueGotcha: redefining only the getter drops the setter
A common mistake is to override a property by writing a new @property in the subclass and expecting the parent's setter to carry over.
class Account:
def __init__(self, balance):
self.balance = balance
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
if value < 0:
raise ValueError("balance cannot be negative")
self._balance = value
class BrokenAccount(Account):
@property
def balance(self):
return self._balance
try:
BrokenAccount(10)
except AttributeError:
print("no setter: __init__ failed")The new @property creates a fresh property object with only a getter. It shadows the parent's property, so the inherited __init__ fails on self.balance = balance. Sometimes this is what you want, for example to make a subtype read-only. Otherwise you need one of the techniques below.
Overriding one part with `Account.balance.getter` and `.setter`
Every property object has getter, setter, and deleter methods. Each returns a copy of the property with that one function replaced and the others kept. Because the @balance.setter syntax inside the parent class is just this call, you can apply it to the parent's property from a subclass.
class Account:
def __init__(self, balance):
self.balance = balance
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
if value < 0:
raise ValueError("balance cannot be negative")
self._balance = value
class LoudAccount(Account):
@Account.balance.getter
def balance(self):
print("reading balance")
return self._balance
acct = LoudAccount(50)
print(acct.balance) # prints "reading balance", then 50
acct.balance = 20 # the inherited setter still works
try:
acct.balance = -1
except ValueError as exc:
print(exc) # balance cannot be negativeAccount.balance.getter(...) builds a new property that has the new getter and the parent's setter. That new property is bound to the name balance in LoudAccount. Account.balance itself is untouched, because properties are immutable in this sense. Plain Account objects still read silently.
Extending the parent's setter
To add behavior around the parent's validation, replace the setter and call the parent's fset function explicitly. The fset attribute holds the raw setter function.
class Account:
def __init__(self, balance):
self.balance = balance
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
if value < 0:
raise ValueError("balance cannot be negative")
self._balance = value
class AuditedAccount(Account):
@Account.balance.setter
def balance(self, value):
print(f"setting balance to {value}")
Account.balance.fset(self, value)
acct = AuditedAccount(100) # prints "setting balance to 100"
acct.balance = 75 # prints "setting balance to 75"
print(acct.balance) # 75The inherited __init__ goes through the subclass setter, so construction is audited too. Note that Account.balance.fset(self, value) names the parent class directly. In a class hierarchy with multiple inheritance this can skip a class that sits between the two in the MRO.
Why `super().balance = value` fails
Reading through super() works, because super().balance looks up the property on the next class in the MRO and calls its getter. Assigning through super() does not work. Assignment on a super object is not forwarded to the parent's descriptor, so Python raises AttributeError.
class Account:
def __init__(self, balance):
self._balance = balance
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
self._balance = value
class Child(Account):
@property
def balance(self):
return super().balance * 2 # reading works
@balance.setter
def balance(self, value):
try:
super().balance = value # assignment does not
except AttributeError:
print("super() cannot be assigned through")
Account.balance.fset(self, value)
c = Child(10)
print(c.balance) # 20
c.balance = 7 # prints the message, then uses fset
print(c.balance) # 14Use Account.balance.fset(self, value) for setters and deleters. Use super().balance for getters.
Gotcha: the property binds the function, not the name
A property stores the function object you give it. It does not look the function up by name at access time. That means overriding a helper method in a subclass has no effect on a property that was built from the parent's version of it.
class Base:
def _get_name(self):
return "base"
name = property(_get_name)
class Child(Base):
def _get_name(self):
return "child"
print(Child().name) # baseChild._get_name exists, but Base.name still holds a reference to the original Base._get_name. The same applies to the decorator form, since @property def name(self) binds that exact function.
If you want subclasses to customize behavior through a hook method, make the property call the hook by name.
class Base:
def _get_name(self):
return "base"
@property
def name(self):
return self._get_name() # looked up on self at access time
class Child(Base):
def _get_name(self):
return "child"
print(Base().name) # base
print(Child().name) # childThis is the template method pattern. The property stays in the base class, and the subclass overrides only the hook.
Other ways a property gets replaced
A property is replaced like any other class attribute, so these cases follow from the same rule.
- A plain class attribute in a subclass (
balance = 0) shadows the parent's property. Instance assignment then writes to the instance__dict__with no validation. - Defining a method named
balancein a subclass also shadows it. - Because a property with a setter is a data descriptor, it takes priority over the instance
__dict__. Assigningself.balance = xin a subclass__init__always goes through the nearest property in the MRO.
Abstract properties
If a base class should require subclasses to provide a property, combine @property with @abstractmethod. Put @property outermost.
from abc import ABC, abstractmethod
class Shape(ABC):
@property
@abstractmethod
def area(self):
...
class Square(Shape):
def __init__(self, side):
self.side = side
@property
def area(self):
return self.side ** 2
print(Square(3).area) # 9
try:
Shape()
except TypeError:
print("cannot instantiate an abstract class")The subclass must define area in its own namespace. If it does not, instantiation fails with TypeError.
Choosing a technique
| Goal | Technique |
|---|---|
| Make a subtype read-only | Redefine with a new `@property` and no setter |
| Change only the getter | `@Parent.attr.getter` |
| Add behavior around validation | `@Parent.attr.setter`, then call `Parent.attr.fset(self, value)` |
| Let subclasses customize computation | Property calls a hook method by name |
| Require subclasses to provide it | `@property` over `@abstractmethod` |
Exercise
Given the class Base with name = property(getname), where getname returns "base", a subclass Child overrides getname to return "child". What does Child().name return, and what is the smallest change to Base that makes it return "child"?
Show answer
It returns "base", because the property holds the original Base.getname function and does not look it up by name. Change the property to call the hook at access time, for example @property def name(self): return self.getname().
Exercise
Write a subclass of Account (from this chapter) called ClampedAccount whose setter replaces negative values with 0 instead of raising ValueError, while keeping the inherited getter. Why can't you reuse Account.balance.fset for the negative case?
Show answer
Use @Account.balance.setter def balance(self, value): self._balance = max(value, 0). The inherited getter is kept because .setter copies the property with only the setter replaced. You cannot call Account.balance.fset for negative values because that function raises ValueError for them. You can call it only for values that are already valid.