【问题标题】:How to obtain an object from a string?如何从字符串中获取对象?
【发布时间】:2013-02-04 18:54:24
【问题描述】:

假设我有以下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>>'
>>> 

现在,有没有办法从字符串&lt;bound method Test.TestFunc of &lt;__main__.Test instance at 0xb771b28c&gt;&gt; 中获取函数句柄。例如,

>>> 
>>> func = xxx(string_func)
>>> func 
<bound method Test.TestFunc of <__main__.Test instance at 0xb771b28c>>
>>> 

【问题讨论】:

  • 如果要将对象序列化为字符串,请使用pickle
  • 您可以从globals()gc.get_objects() 或其他东西构建一个id 字典,然后从中获取实例,然后使用getattr 从实例中获取方法,但是它会非常难看。
  • 这里的实际用例是什么?这闻起来像XY problem。如果你有一种神奇的方法可以从绑定方法reprs 回到原来的绑定方法(甚至以某种方式解决了绑定实例不再存在等明显问题……),你会用它做什么?
  • 如果您只是想在执行f = t.TestFunc 之类的操作后从f 获取tTestFunc,这很容易。 (在 3.x 中是 f.__self__f.__func__,在 2.x 中是 f.im_selff.im_func。)因此,如果您尝试使用 repr 作为获取该信息的复杂方式,您'做错了。

标签: python string object serialization


【解决方案1】:

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

可以回到__main__.Test另一个实例,只要它的构造函数不带任何参数,然后再次查找该方法,但它不会具有相同的内存地址。

您必须为它的组件(模块、类名和方法名)解析字符串,然后在各种组件上使用getattr(),将类作为流程的一部分进行实例化。我怀疑这是你想要的。

【讨论】:

    【解决方案2】:

    有几个陷阱需要考虑:

    • Test 的实例可能不再存在也可能不再存在
    • 该实例可能已被垃圾回收
    • 该实例可能具有猴子修补功能Test.TestFunc
    • 可能已在0xb771b28c 创建了不同的对象

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 再读一遍。这不是问题,OP 想从str(t.TestFunc) 回到t。此外,您使用getattr(带有常量字符串)比没有意义更糟糕。
      猜你喜欢
      • 2019-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-02
      相关资源
      最近更新 更多