Skip to main content
 首页 » 编程设计

python之避免对子类进行重复验证

2025年02月15日14mengfanrong

我有以下 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)) 

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

请您参考如下方法:

使用基类创建一个在子类中使用的检查方法

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)) 

(我使用单个下划线前缀向潜在用户表明这是一个内部方法,并不是类接口(interface)的真正组成部分)

或者甚至更好:创建一个 _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))