i make deep-copy instances of class, without copying definitions , rules of given class.
the intended use is, given have class "originalclass", instances variables storing. while program goes on, want able use previous "snapshots" of originalclass, using values (i wont store new ones there, no rules needed inherited).
the above simple example works, , similar want do:
import copy class vm: #nothing in 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 idea substitute:
vmpast=copy.deepcopy(vm1) for working code dont know how write, copy instances , dictionaries not definitions.
the reason is, when using deepcopy version in program (this way:)
vmpast=copy.deepcopy(vm1) vm1.mymethod(vmpast.mybutton[-1]) it throws following error:
attributeerror: attributesetter instance has no __call__ method because value of:
vmpast.mybutton[-1] is been sent as:
'__deepcopy__' instead of actual substituted value intend... (the button), if vmpast working copy of instances inside vm, work inestad of returning deepcopy! thing is, instances dynamic, dont know in advance names or values original class have @ moment. thank much!
a deep copy never copies class definition, instance attributes.
it instead creates new instance. python instances hold reference class definition. call mymethod on instance:
vmpast.mymethod() provided class has such method.
it specific class prevents successful deep-copy:
class variablemanagerclass: def __getattr__(self, attr): return attributesetter(self, attr) the copy.deepcopy() function looks .__deepcopy__() method on instance, , __getattr__ hook instead returns attributesetter class.
you can prevent testing attr little first:
class variablemanagerclass: def __getattr__(self, attr): if attr.startswith('_'): raise attributeerror(attr) return attributesetter(self, attr) this signals class not handle private attributes or special method names.
Comments
Post a Comment