2013-02-19 62 views
0

说我有以下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.TestFuncPython表示为字符串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>> 
>>> 
+3

如果要将对象序列化为字符串,请使用['pickle'](http://docs.python.org/2/library/pickle.html)。 – Bakuriu 2013-02-19 22:18:48

+1

你可以从'globals()'或者'gc.get_objects()'或者其他东西构建一个'id'字典,然后从中得到实例,然后使用'getattr'从实例中获取方法,但是它会非常难看。 – DSM 2013-02-19 22:20:22

+0

这是一个重复的:http://stackoverflow.com/questions/14968349/textual-reference-of-a-method – JCash 2013-02-19 22:57:11

回答

4

你不能单独使用字符串返回到同一个对象,因为Python没有给你一个通过内存地址查找对象的方法。

可以回去__main__.Test另一例如,提供它的构造函数不带任何参数,并重新抬头的方法,但它不会有相同的内存地址。

您必须为其组件(模块,类名称和方法名称)解析字符串,然后在各个组件上使用getattr(),将该类实例化为过程的一部分。我怀疑这是你想要的。

0

您可以使用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 
+1

再次阅读。这不是问题,OP希望从str(t.TestFunc)回到t。另外,你对getattr(使用常量字符串)的使用比毫无意义的要糟糕。 – delnan 2013-02-19 22:25:35

1

有几个陷阱需要考虑:

  • Test实例可能会或可能不会存在了
  • 实例可能已被垃圾回收
  • 实例可能有功能猴子补丁Test.TestFunc
  • 0xb771b28c可能已创建不同的对象
相关问题