nib*_*shi 5 python oop polymorphism abstract-class abstract-methods
我发现将抽象方法分成两个方法似乎很有用,一个用于公共接口,另一个用于子类重写.
通过这种方式,您可以为输入和输出添加前置条件/后置条件检查,从而可以抵御人为错误.
但我在这里关心的是它是否是蟒蛇可接受的,因为在我的小经验中我从来没有见过像这样的代码.
正常多态性
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,)))
Run Code Online (Sandbox Code Playgroud)
实现方法分开
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
Run Code Online (Sandbox Code Playgroud)
除了您描述的之外,以下是我看到的替代方案:
get_area_from_validated_scale
)。我在我的项目中使用了这种技术。get_area_validate_input
和get_area_validate_output
,并要求实现者在每次实现 时调用这些方法get_area
。@area_validation
其方法定义放在上面。 归档时间: |
|
查看次数: |
142 次 |
最近记录: |