How to copy all python instances to a new class?

风流意气都作罢 提交于 2019-12-13 07:37:13

问题


I would like to make a deep-copy all the instances of a class, but without copying the definitions and rules of given class.

The intended use is, given I have the class "OriginalClass", its instances are the variables I am storing. While the program goes on, I want to be able to use previous "snapshots" of OriginalClass, from which I will only be using the values (I wont store new ones there, so no rules are needed to be inherited).

The above simple example works, and is very similar to what I want to do:

import copy

class VM:
    #nothing in the class
    pass

VM1=VM()
VM1.test=dict()
VM1.test['one']="hello"

def printmytext(VMPast=copy.deepcopy(VM1)):

    g.es(VMPast.test['one'])

VM1.test="Bye"

printmytext() #Returns "hello"

But the idea would be to substitute:

VMPast=copy.deepcopy(VM1)

For the working code I dont know how to write, which will copy the instances and dictionaries but not the definitions.

The reason is, when using the deepcopy version in my program (this way:)

VMPast=copy.deepcopy(VM1)
VM1.MyMethod(VMPast.MyButton[-1])

it throws the following error:

AttributeError: AttributeSetter instance has no __call__ method

Because the value of:

VMPast.MyButton[-1]

Is been sent as:

'__deepcopy__'

Instead of the actual substituted value I would intend... (the button), so if VMPast was already a working copy of the instances inside VM, this would work inestad of returning deepcopy! Another thing is, the instances are dynamic, I dont know in advance the names or values that the original class will have at that moment. Thank you very much!


回答1:


A deep copy never copies the class definition, only the instance attributes.

It instead creates a new instance. Python instances only hold a reference to the class definition. Just call MyMethod on that instance:

VMPast.MyMethod()

provided the class has such a method.

It is your specific class that prevents a successful deep-copy:

class VariableManagerClass:
    def __getattr__(self, attr):
        return AttributeSetter(self, attr)

The copy.deepcopy() function looks for a .__deepcopy__() method on the instance, and your __getattr__ hook instead returns a AttributeSetter class.

You can prevent this by testing your attr a little first:

class VariableManagerClass:
    def __getattr__(self, attr):
        if attr.startswith('_'):
            raise AttributeError(attr)
        return AttributeSetter(self, attr)

This signals that your class does not handle private attributes or special method names.




回答2:


If you only care about the values (attributes) of the class I think you could just call the __dict__ method to get those.

In [1]: class Foo():
   ...:     pass
   ...: 

In [2]: foo = Foo()

In [3]: foo.bar1 = 'derp'

In [4]: foo.bar2 = 'derp derp'

In [5]: foo.__dict__
Out[5]: {'bar1': 'derp', 'bar2': 'derp derp'}

If this is what asking, here is a related question: List attributes of an object



来源:https://stackoverflow.com/questions/17744721/how-to-copy-all-python-instances-to-a-new-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!