0

I'm quite new to object-oriented programming and I'm trying to create random objects by using the Agent() class:

class Agent():


def __init__(self, r = None):
    
    self.model = sa.Anm(model_info)
    
    if r is None:
        for n in range(len(self.model.elems)):
            self.model.elemsSections[n] = np.random.choice(self.model.sections[:,0])
            
    self.fitness = 0
    
    self.model.drawModel()

The self.model attribute reads the model_info .py file containing a "template" with the model's variables. Then, the for loop modifies the model.elemsSections attribute with a random choice of available sections inside the model.sections attribute.

Problem is, as I create the objects, the last instantiation modifies the ones created before. The closest I could get to answer this was in this question here, but with no results.

Maybe it's something with the for loop inside the __init__ function? Somehow, the last for loop executed is applied to the objects created before.

Thanks!

  • You do not give any details about Anm and model_info, so it is a bit of guesswork. It might be unrelated to loops. This looks like a *mutable aliasing* problem, see slides 11-17 in this [presentation](https://www.cs.cmu.edu/~15110-s20/slides/week6-2-aliasing.pdf). Also this [SO answer](https://stackoverflow.com/questions/2465921/how-to-copy-a-dictionary-and-only-edit-the-copy/2465951#2465951). For example, are we sure that each `model` object has its own private `sections` subobject ? Maybe `copy.deepcopy()` can help. Also may I suggest you replace the for-loop tag by the python tag ? – jpmarinier Oct 13 '21 at 18:32
  • @jpmarinier, you solved it. The problem was that I was referencing the same`model` object every iteration, which in that case `copy.deepcopy()` helped. I don't know how to thank you since this was a comment (I think), but thx!!! – guilhermesalgado Oct 13 '21 at 23:05

0 Answers0