1

I have two scripts, one where a class is created and a second loading/plotting script. I have three instances of the same class (T1, T2, and T3) but want to combine them into a single T. When do T=T1, then T+T2 and T+T3, T1 inherits the T2 and T3 instances when I only want T to have all the instances.

I tried modifying my __add__ magic method in my class script as below but the deepcopy doesn't work. The T continues to be empty. However when I do T = deepcopy(T1) in my command window, it works fine. I'd prefer the __add__ method to include this capability.

From class script:

def __add__(self, other):
    """ A "magic" method to overload the '+' operator by
    appending trajectories.
    """
    if len(self.contents) == 0:
        self = deepcopy(other)
    else:
        self.contents.append(other)

I also tried created a new method to directly do the deepcopy, but it also will not copy as expected.

def copy(self,other):
    self = deepcopy(other)

I start with T empty:

In [80]: T.contents
Out[80]: []

But I want T to include T1 through T3 without T1 being identical to T.

In [74]: T.contents
Out[74]: 
[Trajectory Object: MONTE_RUN_mmv13_2D2M_RODupdate
        contains data from FAST,
 Trajectory Object: MONTE_RUN_mmv13_1D2M_RODupdate
        contains data from FAST,
 Trajectory Object: MONTE_RUN_mmv13_2D3M
        contains data from FAST]

Not:

In [74]: T1.contents
Out[74]: 
[Trajectory Object: MONTE_RUN_mmv13_2D2M_RODupdate
        contains data from FAST,
 Trajectory Object: MONTE_RUN_mmv13_1D2M_RODupdate
        contains data from FAST,
 Trajectory Object: MONTE_RUN_mmv13_2D3M
        contains data from FAST]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Leah R.
  • 11
  • 2
  • I don't believe `self = deepcopy(other)` actually makes any change to the object. It merely changes what the local name "self" points to. Once the function ends, it's effectively forgotten. In any case, shouldn't `__add__` return a brand new object, rather than modifying the existing one? It's not like `a+b` modifies `a` when a and b are integers. – Kevin Sep 16 '14 at 14:03
  • possible duplicate of http://stackoverflow.com/questions/2137772/change-class-instance-inside-an-instance-method – d0c Sep 16 '14 at 17:03

0 Answers0