我正在尝试将DRY原则应用于玩具绘图类,作为一种智力练习,以提高我对 OOP 的理解(目前正在阅读Python 面向对象编程),但直观地看,使用潜在的越来越深的继承层次结构可能会导致更复杂的代码库(特别是因为我已经读过组合似乎比继承更受青睐,请参阅组合优于继承 wiki)。似乎这样的玩具库最终可能会有太多的抽象类,如AbstractMonthlyMultiPanelPlot
等等AbstractSeasonalPlot
,用于任意绘图类型以适应不同的输入数据。
有没有一种更符合 Python 风格的方法来处理下面我可能遗漏的问题?我是否违反了某种我误解或完全忽略的设计原则?
from abc import abstractmethod, ABC
from numpy import ndarray
from typing import List, Tuple
import matplotlib.pyplot as plt
class AbstractPlot(ABC)
@abstractmethod
def plot(self):
raise NotImplementedError
class AbstractMonthlyPlot(AbstractPlot):
@abstractmethod
def plot_for_month(ax, data):
raise NotImplementedError
@property
def n_months(self):
"""number of months in a year"""
return 12
def plot(self, month_to_data: List[Tuple[ndarray]]):
fig, axs = plt.subplots(self.n_months, 1)
for month in range(self.n_months):
self._plot_for_month(ax=axs[month], data=month_to_data[month])
class Contour(AbstractMonthlyPlot):
def _plot_for_month(self, ax, data):
ax.contourf(*data)
class Linear(AbstractMonthlyPlot):
def _plot_for_month(self, ax, data):
ax.plot(*data)
1 个回答