如何从对象中获取函数定义?

Joh*_*ohn 4 python

假设我们在tester.py中定义了以下代码

class Tester( object ):
    def method( self ):
        print 'I am a Tester'
Run Code Online (Sandbox Code Playgroud)

我们在main.py中定义了以下内容

from tester import Tester
t = Tester()
#print definition of t
Run Code Online (Sandbox Code Playgroud)

无论如何我们可以系统地从对象中获取类/函数的定义吗?或者我们必须解析代码并手动提取代码定义然后将它们保存到字符串中?

Ada*_*ner 8

您可以使用该inspect模块:

import inspect

class Tester( object ):
    def method( self ):
        print 'I am a Tester'

print inspect.getsource(Tester)
Run Code Online (Sandbox Code Playgroud)

输出:

class Tester( object ):
    def method( self ):
        print 'I am a Tester'
Run Code Online (Sandbox Code Playgroud)