Same Python object created on each iteration

Question:

I have code that creates a "Box" object, with a unique number assigned to each Box, then a unique number assigned as the contents for each Box. multiple boxes then make up a "Room" object.

Here’s the thing, when I run multiple iterations to create a new Room object, each room iteration creates the exact same room object. By running this code, you see that box 0 prints the same for every iteration. Why is that, and how can I get a unique combination of box contents on each iteration?

import random


class Box:
    def __init__(self, box_number, box_content):
        self.number = box_number
        self.content = box_content

    def __str__(self):
        return f"Box: {self.number} | Content: {self.content}"


class Room:
    boxes = []

    def __init__(self, num_of_boxes):
        box_contents = [*range(num_of_boxes)]
        random.shuffle(box_contents)
        for i in range(num_of_boxes):
            self.boxes.append(Box(i + 1, box_contents[i] + 1))


def run_cycle():
    room = Room(5)
    print(room.boxes[0])


for _ in range(5):
    run_cycle()
Asked By: AMcGuffin

||

Answers:

class Room:

    def __init__(self, num_of_boxes):
        self.boxes = []
        ...

def ‘boxes’ inside init belong to an instance.
Your code’s all Room instance has same box attrib which belong to class.

Answered By: ACE Fly
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.