是否可以使用参数自动生成函数?

我有一个方法可以根据形状的名称和一些参数绘制一条线或任何形状的补丁,它工作正常:

def draw_a_shape(ax, is_patch_not_line, shapename, **kwargs):
  ...

现在我需要有 30 多个函数,比如draw_a_square_patchdraw_an_ellipse_outline等等。我可以用一种简单的方式实现它们,如下所示,但这有点痛苦:

def draw_a_square_patch(ax, **kwargs):
  draw_a_shape(ax=ax, is_patch_not_line=True, shapename='a_square', **kwargs)
def draw_a_square_outline(ax, **kwargs):
  draw_a_shape(ax=ax, is_patch_not_line=False, shapename='a_square', **kwargs)
def draw_an_ellipse_patch(ax, **kwargs):
  draw_a_shape(ax=ax, is_patch_not_line=True, shapename='an_ellipse', **kwargs)
def draw_an_ellipse_outline(ax, **kwargs):
  draw_a_shape(ax=ax, is_patch_not_line=False, shapename='an_ellipse', **kwargs)
.........

我想知道是否有办法使用循环来做到这一点,也许像setattr?我在下面添加了一个无效的代码,只是为了解释我的意思:

for shapename in ['a_circle', 'a_square', ...]:
  for is_patch_not_line in [False, True]:
    new_func_name = "draw_" + shapename + "_"
    if is_patch_not_line:
      new_func_name += "patch"
    else:
      new_func_name += "outline"
    global.setattr(new_func_name, "ax, **kwargs", ...) 

回答

functools.partial可用于创建部分对象,它们的作用类似于其他一些已经传递了一些参数的函数。这些可以通过locals()字典在本地命名空间中或通过字典在模块命名空间中给出动态生成的名称globals()(关于字典和其他结构的标准警告globals()在大多数用例中都是有利的,除了这个问题中的特定一个)。

把这些放在一起会给你类似的东西:

for shapename in ['a_circle', 'a_square', ...]:
  for is_patch_not_line in [False, True]:
    new_func_name = "draw_" + shapename + "_"
    if is_patch_not_line:
      new_func_name += "patch"
    else:
      new_func_name += "outline"
    globals()[new_func_name] = functools.partial(
      draw_a_shape,
      shapename=shapename,
      is_patch_not_line=is_patch_not_line,
    )


以上是是否可以使用参数自动生成函数?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>