首页 > 解决方案 > 如何将对象的引用传递给函数以供重用

问题描述

我试图在我的第一个 Python 应用程序中遵守 DRY 原则(我是一位经验丰富的 .NET 开发人员)。我已经能够将大部分重复的代码转移到可重用的函数中。

例如,这是我为 matplotlib 图创建线条(边界框)的方式:

def generate_bounding_box_polygon(comma_delimited_rect: str):
    box_coordinates = comma_delimited_rect.strip().split(',')
    x = int(box_coordinates[0].strip())
    y = int(box_coordinates[1].strip())
    width = int(box_coordinates[2].strip())
    height = int(box_coordinates[3].strip())
    bottom_left = [x, y]
    bottom_right = [x + width, y]
    top_left = [x, y + height]
    top_right = [x + width, y + height]
    points = [bottom_left, top_left, top_right, bottom_right, bottom_left]
    polygon = plt.Polygon(points, fill=None, edgecolor='xkcd:rusty red', closed=False)
    return polygon

我在为我的情节创建边界框时重用它。这个嵌套的 for 循环在几个函数中,所以有这个generate_bounding_boxes函数很好很整洁

for region in result["regions"]:
    region_box = generate_bounding_box_polygon(region["boundingBox"])
    plt.gca().add_line(region_box)

    for line in region["lines"]:
        line_box = generate_bounding_box_polygon(line["boundingBox"])
        plt.gca().add_line(line_box)

        for word in line["words"]:
            detected_text += word
            word_box = generate_bounding_box_polygon(word["boundingBox"])
            plt.gca().add_line(word_box)

            # RELEVANT  this is the code I want to move into a function
            box_coordinates = word["boundingBox"].strip().split(',')
            x = int(box_coordinates[0].strip())
            y = int(box_coordinates[1].strip())
            plt.gca().text(x, y-10, word["text"], fontsize=8)

但是,请注意最后一个代码注释,我还想将该text方法移动到一个函数中,但我需要一个参考plt.gca()

如何将它作为参数传递给函数?我尝试了以下(参见第二个参数,plot),就像我在 C# 中所做的那样,但它不起作用,并且在 python 中可能是不好的做法:

def render_text(comma_delimited_rect: str, plot: matplotlib.pyplot):
    box_coordinates = comma_delimited_rect.strip().split(',')
    x = int(box_coordinates[0].strip())
    y = int(box_coordinates[1].strip())
    plt.gca().text(x, y-10, word["text"], fontsize=8)

注:plt定义为import matplotlib.pyplot as plt

标签: pythonpython-3.xmatplotlib

解决方案


如果您plt.gca()无论如何都在函数内部使用,则不需要附加参数。

def render_text(comma_delimited_rect):
    box_coordinates = comma_delimited_rect.strip().split(',')
    x = int(box_coordinates[0].strip())
    y = int(box_coordinates[1].strip())
    plt.gca().text(x, y-10, word["text"], fontsize=8)

相反,如果您想将要绘制的轴传递到,您可以将其提供给函数

def render_text(comma_delimited_rect, word, axes):
    box_coordinates = comma_delimited_rect.strip().split(',')
    x = int(box_coordinates[0].strip())
    y = int(box_coordinates[1].strip())
    axes.text(x, y-10, word, fontsize=8)

用例如调用它

render_text( word["boundingBox"],  word["text"], plt.gca())

推荐阅读