Tri*_*ych 134
如果要导入该功能,可以使用inspect.getsource:
>>> import re
>>> import inspect
>>> print inspect.getsource(re.compile)
def compile(pattern, flags=0):
"Compile a regular expression pattern, returning a pattern object."
return _compile(pattern, flags)
Run Code Online (Sandbox Code Playgroud)
这将在交互式提示中起作用,但显然仅适用于导入的对象(不是交互式提示中定义的对象).当然,只有Python可以找到源代码(因此不能在内置对象,C库,.pyc文件等上),它才会起作用.
虽然我一般都认为这inspect是一个很好的答案,但我不同意你无法获得解释器中定义的对象的源代码.如果使用dill.source.getsourcefrom dill,则可以获取函数和lambdas的来源,即使它们是以交互方式定义的.它还可以从curries中定义的绑定或非绑定类方法和函数中获取代码...但是,如果没有封闭对象的代码,您可能无法编译该代码.
>>> from dill.source import getsource
>>>
>>> def add(x,y):
... return x+y
...
>>> squared = lambda x:x**2
>>>
>>> print getsource(add)
def add(x,y):
return x+y
>>> print getsource(squared)
squared = lambda x:x**2
>>>
>>> class Foo(object):
... def bar(self, x):
... return x*x+x
...
>>> f = Foo()
>>>
>>> print getsource(f.bar)
def bar(self, x):
return x*x+x
>>>
Run Code Online (Sandbox Code Playgroud)
这是我弄清楚如何做到这一点的方式:
import inspect as i
import sys
sys.stdout.write(i.getsource(MyFunction))
Run Code Online (Sandbox Code Playgroud)
这将取出新行字符并很好地打印出该函数
| 归档时间: |
|
| 查看次数: |
63619 次 |
| 最近记录: |