如何覆盖 `savefig` 方法以便它可以解包元组

How to overwrite `savefig` method so that it can unpack a tuple

我正在对一段代码进行最小扩展。

我有一个 make_fig 函数,它过去只生成一个数字,我会在许多其他函数中将其称为 fig,然后将其保存为 fig.savefig

在扩展中,make_fig 现在 returns 一个 元组 数字。所以,为了保存它们,我现在需要像这样的东西:

fig = make_fig

for f in fig:
   f.savefig

我希望有一个更优雅的解决方案,一个不需要在 make_fig 出现的任何地方添加 for 循环的解决方案。

如果 a 是一个 matplotlib.pytplot 实例,我能否以某种方式修改 a.savefig 方法,使其执行其正常功能,如果它是一个元组,则执行上面的 for 循环?

下面是 MWE。

d = 1 是“旧”代码,d=2 是我要添加的扩展名。

import matplotlib.pyplot as plt 

def make_fig(d):
    if d==1:
        fig, ax = plt.subplots(1)
    elif d==2:
        fig1, ax = plt.subplots(1)
        fig2, ax = plt.subplots(1)
        fig = (fig1, fig2)
    else:
        raise Exception('error')
    return fig

d=2
fig = make_fig(d)
fig.savefig('hello.png')

只需实现您自己的 savefig 函数即可处理这两种情况。

from collections.abc import Iterable

def savefig(filename, fig):
    if not isinstance(fig, Iterable):
        fig = (fig,)
    for i, f in enumerate(fig):
        f.savefig(f'{filename}_{i}.jpg')


fig = make_fig(1)
savefig('test1', fig)
fig = make_fig(2)
savefig('test2', fig)

执行后,我们有test1_0.jpgtest2_0.jpgtest2_1.jpg

作为 if 检查的替代方法,您可以使用 EAFP 方法:

def savefig(filename, fig):
    try:
        fig.savefig(filename)
    except AttributeError:
        for i, f in enumerate(fig):
            f.savefig(f'{filename}_{i}.jpg')

为了做到这一点,您可以 return 您自己的对象,而不是 return 元组,该对象将元组作为字段之一。

class MultipleFigures:

    def __init__(self, figures):
        self.figures = figures

    def savefig(self):
        for fig in self.figures:
            fig.savefig()

make fig 函数可以 return 一个 matplotlib.pytplot 实例或一个 MultipleFigures 实例。