问题
Say I have the following class
class Test:
def TestFunc(self):
print 'this is Test::TestFunc method'
Now, I create an instance of the class Test
>>>
>>> t = Test()
>>>
>>> t
<__main__.Test instance at 0xb771b28c>
>>>
Now, the t.TestFunc
is represented as follows
>>>
>>> t.TestFunc
<bound method Test.TestFunc of <__main__.Test instance at 0xb771b28c>>
>>>
Now I am storing the Python
representation of t.TestFunc
to a string string_func
>>>
>>> string_func = str(t.TestFunc)
>>> string_func
'<bound method Test.TestFunc of <__main__.Test instance at 0xb771b28c>>'
>>>
Now, Is there a way, where I can get the function handle from the string <bound method Test.TestFunc of <__main__.Test instance at 0xb771b28c>>
. For example,
>>>
>>> func = xxx(string_func)
>>> func
<bound method Test.TestFunc of <__main__.Test instance at 0xb771b28c>>
>>>
回答1:
You cannot with the string alone go back to the same object, because Python does not give you a method to look up objects by memory address.
You can go back to another instance of __main__.Test
, provided it's constructor doesn't take any arguments, and look up the method again, but it will not have the same memory address.
You'd have to parse the string for it's components (module, classname, and method name), then use getattr()
on the various components, instantiating the class as part of the process. I doubt this is what you wanted though.
回答2:
There are several pitfalls to consider:
- the instance of
Test
may or may not exist anymore - the instance may have been garbage collected
- the instance may have had the function monkey-patched
Test.TestFunc
- a different object may have been created at
0xb771b28c
回答3:
You can use getattr.
In [1]:
class Test:
def TestFunc(self):
print 'this is Test::TestFunc method'
In [2]: t = Test()
In [3]: getattr(t, 'TestFunc')
Out[3]: <bound method Test.TestFunc of <__main__.Test instance at 0xb624d68c>>
In [4]: getattr(t, 'TestFunc')()
this is Test::TestFunc method
来源:https://stackoverflow.com/questions/14968560/how-to-obtain-an-object-from-a-string