python类的实例复制_如何将所有python实例复制到一个新类?

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!

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值