这两个Python语句有什么区别?

Mon*_*Kin 5 python swig python-2.7

我正在深入研究WiringPi-Python for Python 的代码,我找到了几个像这样的块:

def wiringPiSetup():
  return _wiringpi2.wiringPiSetup()
wiringPiSetup = _wiringpi2.wiringPiSetup
Run Code Online (Sandbox Code Playgroud)

这对我来说有点令人费解,因为我觉得这个:

def wiringPiSetup():
  return _wiringpi2.wiringPiSetup()
Run Code Online (Sandbox Code Playgroud)

会产生与此完全相同的结果:

wiringPiSetup = _wiringpi2.wiringPiSetup
Run Code Online (Sandbox Code Playgroud)

我知道第一个是声明一个新函数,第二个是对原始函数的引用,但在测试中我发现它们完全等价.看这里:

>>> def a():
...     return 4
... 
>>> def a1():
...     return a()
... 
>>> a2 = a
>>> 
>>> a1()
4
>>> a2()
4
Run Code Online (Sandbox Code Playgroud)

那么,为什么WiringPi-Python在它们中任何一个都足够的时候放了?

BTW:

  • 我正在使用Python 2.7.3
  • 这是我看到的文件:这里

Mar*_*ers 3

该文件由SWIG生成。函数定义确实是“死代码”,因为您可以完全删除函数定义并保留赋值。

由于代码是自动生成的,因此代码效率有些低。生成此代码的 SWIG 函数指出:

if (Getattr(n, "feature:python:callback") || !have_addtofunc(n)) {
  /* If there is no addtofunc directive then just assign from the extension module (for speed up) */
  Printv(f_dest, name, " = ", module, ".", name, "\n", NIL);
}
Run Code Online (Sandbox Code Playgroud)

所以第二个任务只是替换生成的Python函数以加快使用速度。

如果函数在生成时需要添加额外的 Python 代码(have_addtofunc()当存在文档字符串、前置或附加值时为 true),则不会生成替换行。

据推测,原始函数保留在原处,以便自动完成工具可以使用函数签名。