如何在python中覆盖对象?

2024-10-02 08:19:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个程序,最明智的做法是重写内存中的对象,而不是更改它,或重定向对它的引用。在

基本上,如果我写C++,我会有多个指针都指向内存中的相同地址。我想改写那个地址的内容。在

我也希望能从对象本身内部做到这一点。在

class MyClass
    def __init__(self):
        pass

    def overwrite(self,otherObjectOfTypeMyClass):
       #after this operation, all references to self now point to otherObjectOfTypeMyClass

Tags: to对象内存self程序内容地址def
3条回答

Python支持多重继承,那么让myClass成为A和{}的包装如何?可能看起来有点过头了,如果A和{}使用相似的接口,那么可以引入diamond problem,但这是我所能想到的最接近于“重写”的。在

好吧,我找到了一个适合我具体使用的解决方案。我不太了解python的内部结构,不知道它是否会以意想不到的方式崩溃。我很想知道这是一件危险的事情。我也很感兴趣,如果有人有任何的想法,在这种情况下,这不会做什么,我期待它。我会等几天把这个标记正确,以防有人认为这实际上是灾难性的。在

def replaceobject(obj1,obj2):
    #Replaces obj1 with obj2
    obj1.__dict__ = obj2.__dict__


class MyClass:
    def __init__(self):
        self.attr0 = None
        self.attr1 = None
        self.attr2 = None
        self.attr3 = None

    def set_some_attrs(self):
        self.attr0 = 0
        self.attr1 = "1"
        self.attr2 = {"2":2}
        self.attr3 = [3]

#Set up scenario, three objects of the same type, one points to a different address
A = MyClass()
A.set_some_attrs()
C = A
B = MyClass()

#Make replacement and spit contents
replaceobject(B,A)
print B.attr0 #=> 0
print B.attr1 #=> "1"
print B.attr2 #=> {"2":2}
print B.attr3 #=> [3]

#Modify the replaced object and changes are reflected
B.attr2 = "made a change"
print A.attr2 #=> "made a change"
print C.attr2 #=> "made a change"

不像C++,内存管理在Python中不受控制。总的来说,这是件好事。对于我们这些从C语言起步的人来说,不必担心内存是一大好处

在python中,我们所说的变量实际上是引用对象的标签。因此,如果您想更改一个不可变的对象(如列表),那么在Python中这应该是现成的。在

但是,在Python中通常不能覆盖对象。创建新对象将使用空闲内存。只有在没有引用内存时,才会对正在使用的内存进行垃圾回收。在

相关问题 更多 >

    热门问题