8

如何用另一个对象替换任何地方的python对象?

我有两个班,SimpleObjectFancyObject。我创建了一个SimpleObject, 并且有几个引用它。现在我想创建一个FancyObject,并使所有这些引用指向新对象。

a = SimpleObject()
some_list.append(a)
b = FancyObject()

a = b不是我想要的,它只是改变了 a 指向的内容。我阅读了以下内容,但没有。我收到错误“属性 __dict__ 不可写”:

a.__dict__ = b.__dict__

我想要的是相当于(伪C):

*a = *b

我知道这很hacky,但是有什么办法可以做到这一点吗?

4

5 回答 5

2

您可以将该对象放在单独模块的全局命名空间中,然后在需要时对其进行修补。

objstore.py

replaceable = object()

sample.py

import objstore

b = object()

def isB():
     return objstore.replaceable is b

if __name__ == '__main__':
     print isB()#False
     objstore.replaceable = b
     print isB()#True

PS 依赖猴子补丁是糟糕设计的症状

于 2013-07-26T09:18:33.030 回答
1

不可能。它会让你改变不可变的对象并导致各种讨厌的事情。

x = 1
y = (x,)
z = {x: 3}
magic_replace(x, [1])
# x is now a list!
# The contents of y have changed, and z now has an unhashable key.

x = 1 + 1
# Is x 2, or [1, 1], or something stranger?
于 2013-07-26T08:46:24.457 回答
1

PyJack有一个函数replace_all_refs可以替换内存中对象的所有引用。

文档中的一个示例:

>>> item = (100, 'one hundred')
>>> data = {item: True, 'itemdata': item}
>>> 
>>> class Foobar(object):
...     the_item = item
... 
>>> def outer(datum):
...     def inner():
...         return ("Here is the datum:", datum,)
...     
...     return inner
... 
>>> inner = outer(item)
>>> 
>>> print item
(100, 'one hundred')
>>> print data
{'itemdata': (100, 'one hundred'), (100, 'one hundred'): True}
>>> print Foobar.the_item
(100, 'one hundred')
>>> print inner()
('Here is the datum:', (100, 'one hundred'))

调用 replace_all_refs

>>> new = (101, 'one hundred and one')
>>> org_item = pyjack.replace_all_refs(item, new)
>>> 
>>> print item
(101, 'one hundred and one')
>>> print data
{'itemdata': (101, 'one hundred and one'), (101, 'one hundred and one'): True}
>>> print Foobar.the_item
(101, 'one hundred and one')
>>> print inner()
('Here is the datum:', (101, 'one hundred and one'))
于 2013-08-14T14:31:40.453 回答
0

您有多种选择:

  1. 从一开始就设计它,使用外观模式(即主代码中的每个对象都是其他东西的代理)或单个可变容器(即每个变量都包含一个列表;您可以通过任何这样的参考)。优点是它与语言的执行机制一起工作,并且相对容易从受影响的代码中发现。缺点:更多代码。
  2. 始终引用相同的单个变量。这是上述的一种实现。干净,没有什么花哨的,代码清晰。到目前为止,我会推荐这个。
  3. 使用 debug、gc 和 introspection 功能来寻找每个满足您的标准的对象并在运行时更改变量。缺点是变量的值会在代码执行期间发生变化,而无法从受影响的代码中发现。即使更改是原子的(消除了一类错误),因为这可以在执行确定该值是不同类型的代码之后更改变量的类型,从而在该代码中引入无法合理预期的错误。例如

    a = iter(b) # will blow up if not iterable
    [x for x in b] # before change, was iterable, but between two lines, b was changed to an int.
    

更微妙的是,在区分字符串和非字符串序列时(因为字符串的定义特征是迭代它们也会产生字符串,它们本身是可迭代的),在展平结构时,代码可能会被破坏。

另一个答案提到了实现选项 3 的pyjack。虽然它可能有效,但它具有提到的所有问题。这可能只适用于调试和开发。

于 2013-08-14T14:46:28.420 回答
0

利用可变对象,例如列表。

a = [SimpleObject()]
some_list.append(a)
b = FancyObject()
a[0] = b

证明这有效:

class SimpleObject():
    def Who(self):
        print 'SimpleObject'

class FancyObject():
    def Who(self):
        print 'FancyObject'

>>> a = [SimpleObject()]
>>> a[0].Who()
SimpleObject
>>> some_list = []
>>> some_list.append(a)
>>> some_list[0][0].Who()
SimpleObject
>>> b = FancyObject()
>>> b.Who()
FancyObject
>>> a[0] = b
>>> some_list[0][0].Who()
FancyObject
于 2013-08-14T14:51:08.990 回答