如何复用Python多类的绘图子对象功能以避免代码重复?
优化方案
方案1:使用Mixin类(推荐)
把绘图相关逻辑封装成独立Mixin类,让需要绘图功能的类继承它,就能彻底避免代码重复,实现功能复用。
import matplotlib.pyplot as plt # 封装绘图功能的Mixin类 class PlotMixin: def _init_plot(self): class PlotFns: def __init__(self, parent): self.parent = parent def plot1(self): plt.plot(self.parent.x, self.parent.y) self.plot = PlotFns(self) # 继承Mixin复用绘图功能 class cls_A(PlotMixin): def __init__(self, a1, a2, a3): self.x = a1 + a2 self.y = a2 + a3 self._init_plot() # 类A专属的属性和方法 class cls_B(PlotMixin): def __init__(self, b1, b2, b3): self.x = b1 + b2 self.y = b2 + b3 self._init_plot() # 类B专属的属性和方法 # 使用示例 A = cls_A(1,2,3) A.plot.plot1() B = cls_B(4,5,6) B.plot.plot1()
注意:原代码里的x、y是局部变量,要改成实例属性self.x、self.y,否则绘图类无法访问到这些数据。
方案2:独立封装绘图函数类
把绘图逻辑完全抽成外部独立类,需要绘图功能的类直接实例化这个类并绑定到自身属性上,逻辑更直观解耦。
import matplotlib.pyplot as plt # 独立的绘图函数类 class PlotFns: def __init__(self, parent): self.parent = parent def plot1(self): plt.plot(self.parent.x, self.parent.y) class cls_A: def __init__(self, a1, a2, a3): self.x = a1 + a2 self.y = a2 + a3 self.plot = PlotFns(self) # 类A专属的属性和方法 class cls_B: def __init__(self, b1, b2, b3): self.x = b1 + b2 self.y = b2 + b3 self.plot = PlotFns(self) # 类B专属的属性和方法 # 使用示例 A = cls_A(1,2,3) A.plot.plot1() B = cls_B(4,5,6) B.plot.plot1()
内容的提问来源于stack exchange,提问作者joseph praful
相关产品推荐
相关产品推荐

