I found it seems useful to separate abstract method into two methods, one for public interface, the other to be overridden by subclasses.
This way you can add precondition / postcondition check for both input and output, making it robust against human errors.
But my concern here is whether it is pythonically acceptable or not, because in my little experience I've never seen code like this.
Normal polymorphism
import abc
class Shape:
"""Abstract base class for shapes"""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def get_area(self, scale):
"""Calculates the area of the shape, scaled by a factor.
Do not blame for a silly example.
"""
pass
class Rectangle(Shape):
def __init__(self, left, top, width, height):
self.left = left
self.top = top
self.width = width
self.height = height
def get_area(self, scale):
return scale * self.width * self.height
print(Rectangle(10, 10, 40, 40).get_area(3))
# Gosh!... gets tons of 3's
print(Rectangle(10, 10, 40, 40).get_area((3,)))
Implementation method separated
import abc
class Shape:
"""Abstract base class for shapes"""
__metaclass__ = abc.ABCMeta
def get_area(self, scale):
"""Calculates the area of the shape, scaled by a factor"""
# preconditions
assert isinstance(scale, (int,float))
assert scale > 0
ret = self._get_area_impl(scale)
# postconditions
assert isinstance(ret, (int,float))
assert ret > 0
return ret
@abc.abstractmethod
def _get_area_impl(self, scale):
"""To be overridden"""
pass
class Rectangle(Shape):
def __init__(self, left, top, width, height):
self.left = left
self.top = top
self.width = width
self.height = height
def _get_area_impl(self, scale):
return scale * self.width * self.height
print(Rectangle(10, 10, 40, 40).get_area(3))
print(Rectangle(10, 10, 40, 40).get_area((3,))) # Assertion fails