4

I have come across this python behavior that looks counterintuitive at first sight: I have two objects, Simulation and SimulationResults, defined as follows:

class Simulation:
    def run_sim_1(self):
        results_logger_1 = SimulationResults()
        for _ in range(10):
            results_logger_1.append(1)
        return results_logger_1

    def run_sim_2(self):
        results_logger_2 = SimulationResults()
        for _ in range(10):
            results_logger_2.append(2)
        return results_logger_2

class SimulationResults:
    results = []

    def append(self,n):
        self.results.append(n)

Within the two Simulation methods, I instantiate a SimulationResult object: results_logger_1 and results_logger_2. My expectation was that these two instances would have been defined within the context of each method and then brought outside of it by returning them, therefore I would have expected two clearly defined instances.

However, when I run the code, it turns out that the two instances seem to be (or point at) the same object.

sim_1= Simulation()
results_1 = sim_1.run_sim_1() 
print(len(results_1.results)) # 10, as expected right!
print(results_1.results) # [1,1,1,1,1,1,1,1,1,1] also as expected

results_2 = sim_1.run_sim_2()
print(len(results_2.results)) # this is 20, rather than 10
print(results_2.results) # [1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2] - I would have expected [2,2,2,2,2,2,2,2,2,2]

Why is this happening and how can I obtain two separate instances of the object?

I also have checked results_1 and results_2 memory address and it's different, plus the same behaviors appear when I instantiate a different Simulation object

sim_2 = Simulation()
results_3 = sim_2.run_sim_2()
print(len(results_3.results)) # this becomes 30!
arabinelli
  • 1,006
  • 1
  • 8
  • 19

1 Answers1

6

SimulationResults.results is a class attribute shared by all instances. Make it an instance attribute instead.

class SimulationResults:
    def __init__(self):
        self.results = []

    def append(self,n):
        self.results.append(n)
Random Davis
  • 6,662
  • 4
  • 14
  • 24
chepner
  • 497,756
  • 71
  • 530
  • 681