2

I am trying to load a whole class instance via dill rather than dump and load each class variable one at a time.

Can anybody show me how to do 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)
        a = Object()
        a.DATA = "new value"
        self.CA = a
        print self.CA.DATA

CA = ClassA()
CB = ClassB(CA)
CB.updateValue()
print CA.DATA

So that the output is:

new value
new value
someuser
  • 2,279
  • 4
  • 28
  • 39

2 Answers2

2

I think you're asking:

Given object A and object B, how can I copy all of A's attributes to B in one step (or programatically)?

Naive approach:

B.__dict__ = dict(A.__dict__) # make a copy so objects don't share same dict

The problem with this approach is that it clobbers any preexisting attributes in B that did not exist in A. eg.

B.attr = "some value"
B.__dict__ = dict(A.__dict__)
print(hasattr(B, "attr")) # expect False

A better approach. This approach copies over A's attributes and leaves any attributes that exist on B, but not on A, alone.

B.__dict__.update(A.__dict__)

However, there are still problems if there are attributes on A's class and its parent classes that you want to copy over. But I think that's a different question.

Dunes
  • 37,291
  • 7
  • 81
  • 97
  • I'm the dill author. I don't think you need serialization for this, unless you are looking to persist the objects across sessions. @Dunes shows the more appropriate route. – Mike McKerns May 14 '15 at 13:39
1

In your updateValue

def updateValue(self):
    self.ca.DATA = "new value"
Tasos Vogiatzoglou
  • 2,393
  • 12
  • 16