You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将函数作为参数传递并使其调用原函数的内部参数?

函数作为参数传递并访问原函数内部参数的实现方法

当然可以实现,你原来的代码问题出在函数参数的定义语法错误。正确的做法是把函数作为普通参数传入,然后在原函数内部调用这个传入的函数时,把内部参数作为参数传递过去。

修正后的基础示例

def fn2(a: str):
    print("fn2 string print", a)

def fn1(fn):  # 直接将函数作为参数,不要加()
    b = "fn1 string going to pass to fn2"
    fn(b)  # 调用传入的函数,把内部参数b传进去

fn1(fn2)  # 调用fn1,传入fn2函数

运行这段代码会输出:fn2 string print fn1 string going to pass to fn2


实际绘图场景的改造实现

你的frame_region_plot函数参数定义有误(**fn是错误语法,**仅用于接收关键字参数,无法用来接收函数),需要调整参数结构,让它能接收绘图函数(比如ax_regions)以及对应的数据。下面是改造后的完整代码:

import os
import numpy as np
import matplotlib.pyplot as plt
from typing import Union, Dict

colors = {
    "royalblue": (25, 41, 88),
    "pink": (255, 192, 203),
    "darkorange": (100, 55, 0),
    "indianred": (205, 92, 92),
    "forestgreen": (34, 139, 34),
    "dimgrey": (105, 105, 105),
}

def ax_regions(
    sgm_dict: Dict,
    ax: plt.Axes,
) -> plt.Axes:
    """
    Plot the regions for a dictionary of regions (keys)
    and coordinates (values)

    Args:
        - sgm_dict (dict): segment dictionary with region and coordinates
        - ax (plt.Axes): axes to write onto

    """
    for idx, (sname, scoords) in enumerate(sgm_dict.items()):
        ax.plot(
            scoords[:, 0], scoords[:, 1], label=sname, color=list(colors.keys())[idx]
        )
    return ax

def frame_region_plot(
    frame: np.ndarray,
    *plot_funcs_with_data,  # 接收多个(绘图函数, 对应数据)的元组
    title: str = "Plot",
    fname: Union[str, bool] = False,
    savedir: Union[str, bool] = False,
):
    """Regions plot

    Args:
        - frame (np.ndarray): image to overlay the region onto
        - plot_funcs_with_data: 可变参数,每个元素是(绘图函数, 对应数据)的元组
        - title (str): title of the plot
        - fname (Union[str, bool], optional): File name when saving. Defaults to False.
        - savedir (Union[str, bool], optional): Saving directory path. Defaults to False.
    """
    fig, ax = plt.subplots()
    plt.imshow(frame, cmap="bone")

    # 遍历每个绘图函数和对应的数据,调用函数并传入内部创建的ax
    for func, data in plot_funcs_with_data:
        func(data, ax)

    plt.title(title)

    handles, labels = plt.gca().get_legend_handles_labels()
    by_label = dict(zip(labels, handles))
    plt.legend(by_label.values(), by_label.keys())

    plt.tight_layout()

    if savedir and fname:  # 增加非空判断,避免无效保存
        os.makedirs(savedir, exist_ok=True)  # 确保保存目录存在
        save_path = os.path.join(savedir, f"{fname}.png")
        plt.savefig(save_path)
    plt.show()

使用示例

假设你有测试数据,调用方式如下:

# 模拟测试数据
test_frame = np.random.rand(200, 200)  # 随机生成200x200的图像
test_sgm_dict = {
    "region1": np.array([[10,10], [50,50], [10,50]]),
    "region2": np.array([[100,100], [150,150], [100,150]])
}

# 调用frame_region_plot,传入ax_regions和对应的数据
frame_region_plot(
    test_frame,
    (ax_regions, test_sgm_dict),
    title="Test Region Plot",
    fname="test_plot",
    savedir="./plots"
)

关键修改点说明

  1. 参数结构调整:将*data, **fn改为*plot_funcs_with_data,每个参数元素是绘图函数+对应数据的元组,支持灵活传入多个不同的绘图函数和数据。
  2. 内部调用逻辑:循环取出函数和数据,直接调用func(data, ax),把原函数内部创建的ax传递给绘图函数使用。
  3. 保存逻辑修复:使用os.path.join正确拼接路径,增加目录存在性检查,避免因目录不存在报错,同时增加参数非空判断防止无效保存。

内容的提问来源于stack exchange,提问作者Unic0

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 17:39:54