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
重新绑定(bind)到新对象。通常,对裸名的赋值不会改变任何对象,它只是重新绑定(bind)左侧的名称以指向右侧的对象。
所以您需要做的是修改对象 self
指向以匹配对象 self.o
指向。这只有在 A
和 Wrapper
都是新式类并且它们都没有定义 __slots__
时才有可能:
self.__class__ = self.o.__class__
self.__dict__ = self.o.__dict__
这将在 CPython 中工作,但我不确定其他 Python 实现。即使在 CPython 中,这样做也是一个糟糕的主意。
(请注意,代码最后一行中的 is
条件仍将为 False
,但我认为这符合您的预期。)
关于python - 是否可以覆盖 "self"以指向 python 中 self.method 中的另一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7940470/