class - Python changing ClassA instance variables in ClassB -
i trying load whole class instance via dill rather dump , load each class variable 1 @ time.
can show me how this:
class object(object): pass class classa: def __init__(self): self.data = "initial" class classb: def __init__(self, ca): self.ca = ca def updatevalue(self): #a = dill.load(classa.storage) = object() a.data = "new value" self.ca = print self.ca.data ca = classa() cb = classb(ca) cb.updatevalue() print ca.data
so output is:
new value new value
i think you're asking:
given object , object b, how can copy of a's attributes b in 1 step (or programatically)?
naive approach:
b.__dict__ = dict(a.__dict__) # make copy objects don't share same dict
the problem approach clobbers preexisting attributes in b did not exist in a. eg.
b.attr = "some value" b.__dict__ = dict(a.__dict__) print(hasattr(b, "attr")) # expect false
a better approach. approach copies on a's attributes , leaves attributes exist on b, not on a, alone.
b.__dict__.update(a.__dict__)
however, there still problems if there attributes on a's class , parent classes want copy over. think that's different question.
Comments
Post a Comment