说我有以下class
如何从字符串中获取对象?
class Test:
def TestFunc(self):
print 'this is Test::TestFunc method'
现在,我创建的class Test
>>>
>>> t = Test()
>>>
>>> t
<__main__.Test instance at 0xb771b28c>
>>>
现在的情况下,t.TestFunc
如下
>>>
>>> t.TestFunc
<bound method Test.TestFunc of <__main__.Test instance at 0xb771b28c>>
>>>
现在我保存表示t.TestFunc
的Python
表示为字符串string_func
>>>
>>> string_func = str(t.TestFunc)
>>> string_func
'<bound method Test.TestFunc of <__main__.Test instance at 0xb771b28c>>'
>>>
现在,有没有一种方法,在那里我可以从字符串<bound method Test.TestFunc of <__main__.Test instance at 0xb771b28c>>
得到函数句柄。例如,
>>>
>>> func = xxx(string_func)
>>> func
<bound method Test.TestFunc of <__main__.Test instance at 0xb771b28c>>
>>>
如果要将对象序列化为字符串,请使用['pickle'](http://docs.python.org/2/library/pickle.html)。 – Bakuriu 2013-02-19 22:18:48
你可以从'globals()'或者'gc.get_objects()'或者其他东西构建一个'id'字典,然后从中得到实例,然后使用'getattr'从实例中获取方法,但是它会非常难看。 – DSM 2013-02-19 22:20:22
这是一个重复的:http://stackoverflow.com/questions/14968349/textual-reference-of-a-method – JCash 2013-02-19 22:57:11