class Wrapper(object):
def __init__(self, o):
# get wrapped object and do something with it
self.o = o
def fun(self, *args, **kwargs):
self = self.o # here want to swap
# or some low level C api like
# some_assign(self, self.o)
# so that it swaps id() mem addr to self.o
return self.fun(*args, **kwargs) # and now it's class A
class A(object):
def fun(self):
return 'A.fun'
a = A()
w = Wrapper(a)
print(type(w)) # wrapper
print(w.fun()) # some operation after which I want to loose Wrapper
print(a is w) # this goes False and I'd like True :)
# so that this is the original A() object
有没有办法在Python中做到这一点?
分配给self
在方法内部只需重新绑定局部变量self
到新对象。通常,对裸名称的赋值永远不会更改任何对象,它只是重新绑定左侧的名称以指向右侧的对象。
所以你需要做的是修改对象self
指向匹配对象self.o
指着。这只有在两者都存在的情况下才有可能A
and Wrapper
是新式类,它们都没有定义__slots__
:
self.__class__ = self.o.__class__
self.__dict__ = self.o.__dict__
这将在 CPython 中工作,但我不确定其他 Python 实现。即使在 CPython 中,这样做也是一个糟糕的主意。
(请注意,is
代码最后一行的条件仍然是False
,但我认为这符合您的意图。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)