Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the function definition from an object?

Tags:

python

Suppose we have following code defined in tester.py

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

and we have following defined in main.py

from tester import Tester
t = Tester()
#print definition of t

is there anyway we could get the definitions of a class/function from an object in a systematic way? or we have to parse the code and extract the code definition manually then save them into a string?

like image 586
John Avatar asked Jan 19 '23 09:01

John


1 Answers

You can use the inspect module:

import inspect

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

print inspect.getsource(Tester)

Output:

class Tester( object ):
    def method( self ):
        print 'I am a Tester'
like image 113
Adam Wagner Avatar answered Jan 29 '23 20:01

Adam Wagner