如何基于外部条件调用实例不同绑定方法(Matplotlib示例)
优化Matplotlib循环绘图的条件判断逻辑
嘿,这个场景我太熟了——循环里反复判断同一个固定条件,不仅代码啰嗦,看着也闹心!咱们完全可以把判断逻辑提前抽出来,直接绑定好要调用的方法,循环里只管调用就行,不用每次都做判断。
先给你看看原来的冗余写法,就是你提到的循环内每次判断draw_log的情况:
import matplotlib.pyplot as plt x, y = [1,2,3], [10, 200, 1] fig, ax_lst = plt.subplots(3, 2) draw_log = False # 原来的写法:循环内重复判断条件 for ax_row in ax_lst: for ax in ax_row: if draw_log: ax.loglog(x, y) else: ax.plot(x, y)
优化方案:提前绑定绘图方法,只判断一次
核心思路是:既然draw_log是外部固定参数,不会在循环里变化,那我们只需要在循环前做一次判断,把要调用的绘图逻辑封装好,循环里直接调用就行。
方法1:用包装函数封装(可读性最好)
这种写法最直观,新手也能一眼看懂:
import matplotlib.pyplot as plt x, y = [1,2,3], [10, 200, 1] fig, ax_lst = plt.subplots(3, 2) draw_log = False # 提前根据条件确定绘图逻辑,只判断一次 if draw_log: def plot_on_axis(ax): ax.loglog(x, y) else: def plot_on_axis(ax): ax.plot(x, y) # 循环里直接调用,无需再判断 for ax_row in ax_lst: for ax in ax_row: plot_on_axis(ax)
方法2:用Lambda简化代码(更紧凑)
如果想让代码更短,可以用Lambda表达式来包装,效果完全一致:
import matplotlib.pyplot as plt x, y = [1,2,3], [10, 200, 1] fig, ax_lst = plt.subplots(3, 2) draw_log = False # 一行搞定方法绑定 plot_on_axis = (lambda ax: ax.loglog(x, y)) if draw_log else (lambda ax: ax.plot(x, y)) # 循环调用 for ax_row in ax_lst: for ax in ax_row: plot_on_axis(ax)
方法3:直接使用未绑定的类方法(进阶玩法)
如果你对Python的方法绑定机制熟悉,也可以直接用Matplotlib的Axes类的未绑定方法,调用时把轴实例作为第一个参数传入:
import matplotlib.pyplot as plt x, y = [1,2,3], [10, 200, 1] fig, ax_lst = plt.subplots(3, 2) draw_log = False # 选择对应的类方法 plot_func = plt.Axes.loglog if draw_log else plt.Axes.plot # 循环调用时传入轴实例 for ax_row in ax_lst: for ax in ax_row: plot_func(ax, x, y)
为什么要这么做?
- 减少冗余判断:判断逻辑只执行一次,不用在循环里重复跑,虽然这里性能影响不大,但代码更干净利落。
- 提升可维护性:以后如果要加更多绘图模式(比如半对数
semilogx/semilogy),只需要修改循环外的判断逻辑,不用动循环内的代码。 - 通用性强:这个思路不止适用于Matplotlib,任何需要根据外部固定条件选择不同实例方法调用的场景都能用,本质是把方法选择和执行逻辑解耦。
内容的提问来源于stack exchange,提问作者percusse
相关产品推荐
相关产品推荐

