繁体   English   中英

Python - 内部函数,闭包和工厂函数 - 如何分解?

[英]Python - Inner Functions, Closures, and Factory Functions - how to factor out?

我希望那里的Python专家可以为我目前在内部功能,闭包和工厂功能方面遇到的困惑提供一些帮助。 在寻找General Hough Transform的实现示例时,我发现了这个:

https://github.com/vmonaco/general-hough/blob/master/src/GeneralHough.py

我想把它翻译成C ++,似乎第一步是将general_hough_closure()中的内部函数分解出来:

def general_hough_closure(reference_image):
    '''
    Generator function to create a closure with the reference image and origin
    at the center of the reference image

    Returns a function f, which takes a query image and returns the accumulator
    '''
    referencePoint = (reference_image.shape[0]/2, reference_image.shape[1]/2)
    r_table = build_r_table(reference_image, referencePoint)

    def f(query_image):
        return accumulate_gradients(r_table, query_image)

    return f

我似乎被困在这个功能如何工作。 似乎没有在任何地方调用“f”,我不确定函数如何知道“query_image”是什么? 我尝试了各种谷歌搜索,找到关于内部功能,闭包和工厂功能的提示,例如这个和一些类似的页面,但我能找到的所有例子都更加简化,因此没什么帮助。 任何人都可以提供一些方向吗?

代码只是返回函数f作为一个整体。 没有必要“知道论证是什么” - f在被调用时会知道它。 经典的例子是这样的:

>>> def f(x):
...     def g(y):
...         return x + y
...     return g
... 
>>> f
<function f at 0x7f8500603ae8>
>>> f(1)
<function f.<locals>.g at 0x7f8500603a60>
>>> s = f(1)
>>> s(2)
3

这里,就像你的函数一样, g 关闭另一个值(分别是xr_table ),同时仍然期望它的实际参数。

由于存在封闭值,因此无法直接分解f 一种传统的方法是返回一个包含该值的对象,该对象具有某种表示该函数的调用方法; 现在C ++中更简单的方法是使用lambda函数:

int f(int x) {
  auto g = [x](int y) {
    return x + y
  };
  return g;
}

在C ++中,如果不指定要关闭的值(这是[x]这里),你会有“优势”它会对你大喊大叫。 但是在内部,它几乎完全相同(构建一个带有x -member的匿名类)。

C ++ 11之前的C ++没有类型的函数。

您可以使用以下类来模拟语义(伪代码):

class GeneralHoughClosure {
  public:
    GeneralHoughClosure(reference_image) {
      referencePoint = (reference_image.shape[0]/2, reference_image.shape[1]/2)
      r_table = build_r_table(reference_image, referencePoint)
    }
    void Run(queryImage) {
      return accumulate_gradients(r_table, query_image)
    }
    void operator()(queryImage) {
      return accumulate_gradients(r_table, query_image)
    }        
  }

然后,您可以按如下方式使用它:

gg = new GeneralHoughClosure(reference_image)
gg.Run(queryImage1)
gg(queryImage2)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM