Sub topic 6
Abstract properties
This chapter assumes you know @property, basic decorators, and how @abstractmethod blocks instantiation of incomplete subclasses.
Why make a property abstract
Sometimes an interface needs a value, not an action. A balance, a name, or a size is read like an attribute, but each subclass computes it differently. An abstract property states that requirement. Every concrete subclass must provide balance, and Python refuses to create objects of classes that don't.
Declaring one
Put @property above @abstractmethod. The order matters, because @abstractmethod has to wrap the plain function first and @property then wraps the result.
from abc import ABC, abstractmethod
class Account(ABC):
@property
@abstractmethod
def balance(self) -> int:
"""Current balance in cents."""
def summary(self) -> str:
return f"Balance: {self.balance / 100:.2f}"
class SavingsAccount(Account):
def __init__(self, cents: int) -> None:
self._cents = cents
@property
def balance(self) -> int:
return self._cents
class Incomplete(Account):
pass
print(SavingsAccount(1250).summary())
try:
Incomplete()
except TypeError as exc:
print("TypeError raised:", type(exc).__name__)summary is a concrete method that reads self.balance. It works for any subclass because the abstract property guarantees the name exists.
How Python decides a property is abstract
When a class is created, ABCMeta looks at every name in the class body. A name is abstract if its value has a true __isabstractmethod__ attribute. A property reports True when its getter, setter, or deleter is abstract. For inherited names, Python checks whether the subclass has replaced them with something that is not abstract.
flowchart TDThe set of abstract names is computed once, when the class is defined. The check itself happens at instantiation.
Ways to satisfy the requirement
The replacement does not have to be a property. Any non-abstract value defined in the class body clears the name.
from abc import ABC, abstractmethod
class Named(ABC):
@property
@abstractmethod
def name(self) -> str: ...
class WithProperty(Named):
@property
def name(self) -> str:
return "property"
class WithClassAttribute(Named):
name = "class attribute"
class WithInstanceAttribute(Named):
def __init__(self) -> None:
self.name = "instance attribute"
print(WithProperty().name)
print(WithClassAttribute().name)
try:
WithInstanceAttribute()
except TypeError:
print("instance attribute does not count")WithInstanceAttribute fails because the check runs before __init__. At that point the class still inherits the abstract name. If subclasses need to set the value per instance, define a property that reads a private attribute, as SavingsAccount does.
Abstract setters
To require a writable property, mark each accessor abstract. The setter decorator goes above @abstractmethod, in the same position as @property.
from abc import ABC, abstractmethod
class Settings(ABC):
@property
@abstractmethod
def level(self) -> int: ...
@level.setter
@abstractmethod
def level(self, value: int) -> None: ...Common mistakes
- Reversing the decorators (
@abstractmethodabove@property) leaves the property non-abstract, so nothing is enforced. - Forgetting that
Incomplete()fails only when called, not when the class is defined. - Setting the value in
__init__instead of defining it in the class body.
Exercise
A base class declares @property @abstractmethod def size(self). A subclass sets self.size = 10 inside __init__ and defines nothing else named size. What happens when you create the subclass, and how do you fix it?
Show answer
Python raises TypeError. The subclass body never replaced the abstract size, and the check runs before __init__. Fix it by defining a property in the class body, for example @property def size(self): return self._size, or by assigning a class attribute such as size = 10.