【发布时间】:2011-10-29 17:26:03
【问题描述】:
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 中做到这一点?
【问题讨论】:
-
@outis 是的,得到:
main.Wrapper'>, A.fun, False -
可以像这样做一些奇怪的事情。我不确定我是否应该告诉你怎么做,因为人们实际上可能会开始做这样可怕的事情。
-
如果我没听错的话,你想要一个与 Smalltalk 的 '#become:' 等效的东西吗?谷歌搜索给了我:wargle.blogspot.com/2009/07/smalltalks-become-in-python.html。 (也就是说代码给我灌输了暴力冲动。)
-
@Inerdia:该代码不仅具有伪装性,甚至不能用于此目的 -
is仍将是False。 -
你想完成什么?
标签: python python-c-api