Abstract property
- Python course
- Intermediate
- Lesson 49/116
- 4 min
Learn abstract properties with @abstractproperty.
Abstract property
To make an attribute abstract, you stack @property with @abstractmethod. @property goes on top, @abstractmethod below. This forces the subclass to fill in the property.
Example: @property\n@abstractmethod\ndef area(self):\n pass. The subclass fills area with @property. So shape.area works for every subclass; each provides its own area computation.
The subclass fills it in
The subclass fills the abstract property with @property. The pass body in the abstract class is replaced by a real computation. When the subclass instance is created, obj.area returns this computation.
Example: class Square(Shape):\n def __init__(self, side):\n self.side = side\n @property\n def area(self):\n return self.side ** 2. Square(3).area returns 9. If area is not filled, Square stays abstract and cannot be instantiated.
Practice Shape abstract area, Square fills it
Start with from abc import ABC, abstractmethod. Define the abstract class Shape(ABC); inside, use @property, @abstractmethod and def area(self): with pass. Then define class Square(Shape):; write def __init__(self, side): and self.side = side. Add @property with def area(self): and return self.side ** 2. Finally create s = Square(3) and print with print(s.area).
Starter code
# Write the Shape abstract class and the Square subclassSample solution
# Write the Shape abstract class and the Square subclass
from abc import ABC, abstractmethod
class Shape(ABC):
@property
@abstractmethod
def area(self):
pass
class Square(Shape):
def __init__(self, side):
self.side = side
@property
def area(self):
return self.side ** 2
s = Square(3)
print(s.area)Expected output
9
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the decorator order for an abstract property?
- First @abstractmethod, then @property
- Only @abstractmethod is enough
- Only @property is enough
- First @property, then @abstractmethod Correct answer
Explanation: @property on top, @abstractmethod below.
2 subclass @property line
class Square(Shape):
def __init__(self, side):
self.side = side
____
def area(self):
return self.side ** 2
class Square(Shape):
def __init__(self, side):
self.side = side
@property
def area(self):
return self.side ** 2
Explanation: The subclass fills area with @property.
3 Match the abstract property parts
| Term | Meaning |
|---|---|
@property |
Top decorator |
@abstractmethod |
Bottom decorator |
def area(self) |
Abstract signature |
return self.side ** 2 |
Implemented body |