废话不多说,就贴一段小代码:
#coding=utf-8
u"""
@summary: python introspection
@date: 2011-7-7
@author: zl
"""
code = """
print 'define class ABC'
class ABC():
def show(self):
print 'this is ABC!'
"""
def test_func():
print 'compile code!'
cobj = compile(code, '', 'exec')
print 'exec cobj!'
exec cobj # or exec code
local_vars = locals()
if (local_vars.has_key('ABC')):
print 'new ABC!'
abc = ABC()
abc.show()
def test_func2():
def foo():
print 'this is foo!'
print 'eval foo!'
obj = eval('foo')
if (isinstance(obj, type(foo))):
obj()
if __name__ == '__main__':
test_func()
test_func2()