我在课堂上遇到了一个方法。当我试图在ipython中找到该方法的源代码时,我得到如下信息:
In [9]: model.elementary_rates??
Type: function
String form: <function elementary_rates at 0x06864170>
File: Dynamically generated function. No source code available.
Definition: model.elementary_rates(rate_constants, theta, p, mpf, matrix)
Docstring: <no docstring>
什么是&#34;动态生成的功能&#34;?你能给我一些信息或例子吗?
答案 0 :(得分:2)
该功能未在文件中定义,但它是动态创建的,例如:
>>> globals()['f'] = lambda: 3
>>>
>>> f
<function <lambda> at 0x10f337cf8>
>>> f()
3
>>> import inspect
>>> inspect.getsource(f)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 701, in getsource
lines, lnum = getsourcelines(object)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 690, in getsourcelines
lines, lnum = findsource(object)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 538, in findsource
raise IOError('could not get source code')
IOError: could not get source code
有多种创建函数的方法,但是如果无法检索源代码(例如模块,文件名,文件中的位置等),则可以将该函数视为动态生成的函数。
以下行创建一个名为f
的函数,该函数在调用时返回值3:
globals()['f'] = lambda: 3
globals()
调用意味着它被添加到全局命名空间,这是您在解释器运行时所处的位置。
答案 1 :(得分:2)
你可以得到一个动态生成的功能&#34;如果该函数是由exec
:
In [34]: code = compile('def f():\n return 3', '<string>', 'exec')
In [35]: exec code
In [36]: f?
Type: function
String Form:<function f at 0x7f6db467ac80>
File: Dynamically generated function. No source code available.
Definition: f()
Docstring: <no docstring>