避免对子类进行重复验证

时间:2017-02-07 21:05:46

标签: python oop

我有以下Python 3.6代码:

import abc
import math
from abc import ABC


class Shape(ABC):
    @abc.abstractmethod
    def draw(self, area):
        pass


class Square(Shape):
    def draw(self, area):
        if area < 0:
            raise ValueError('Area must be greater or equal than 0.')

        print('Square. Side length: %s' % math.sqrt(area))


class Circle(Shape):
    def draw(self, area):
        if area < 0:
            raise ValueError('Area must be greater or equal than 0.')

        print('Circle. radius: %s' % math.sqrt(area / math.pi))

如何避免在每个子类上重复相同的验证?

1 个答案:

答案 0 :(得分:1)

使用基类创建一个在子类

中使用的检查方法
import abc
import math
from abc import ABC


class Shape(ABC):
    @abc.abstractmethod
    def draw(self, area):
        pass
    def _check_area(area):
        if area < 0:
            raise ValueError('Area must be greater or equal than 0.')


class Square(Shape):
    def draw(self, area):
        self._check_area(area)
        print('Square. Side length: %s' % math.sqrt(area))


class Circle(Shape):
    def draw(self, area):
        self._check_area(area)
        print('Circle. radius: %s' % math.sqrt(area / math.pi))

(我使用单个下划线前缀来表示潜在用户它是一个内部方法,而不是真正属于类接口的一部分)

或者甚至更好:创建一个_draw内部方法,一个是抽象的,而不是draw方法。因此,您可以检查draw中的区域并在基类中调用_draw

import abc
import math
from abc import ABC


class Shape(ABC):
    def draw(self, area):
        if area < 0:
            raise ValueError('Area must be greater or equal than 0.')
        self._draw

    @abc.abstractmethod
    def _draw(self, area):
        pass


class Square(Shape):
    def _draw(self, area):
        print('Square. Side length: %s' % math.sqrt(area))


class Circle(Shape):
    def _draw(self, area):
        print('Circle. radius: %s' % math.sqrt(area / math.pi))