gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:14:37 24 4
gpt4 key购买 nike

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

关于python - 避免对子类进行重复验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42099994/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com