python - 是否可以覆盖 "self"以指向 python 中 self.method 中的另一个对象?

标签 python python-c-api

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 指向。这只有在 AWrapper 都是新式类并且它们都没有定义 __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/

相关文章:

python - 程序第二次运行时 multiarray.pyd 出现未处理的异常

c - 如何在 Python C API 中获取返回的 PyObject 的指针?

Python:将参数发送给字典中的函数

Python 如何在 numpy 数组中查找第一个重复项

Python 流中的最后三项

python - 用于读取大型 parquet/csv 文件的 Pytorch Dataloader

python - 缺少 python 3 API 函数

python - 如何将 const char* 从 python 传递给 c 函数

c++ - long int* 到 np_intp* 平台相关转换

python - import 是否在路径之前先查找当前工作目录?或者cwd的路径?