0

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()
YangTegap
  • 381
  • 1
  • 11
  • 1
    if you change ```print(room.boxes[0])``` in ```run_cycle``` to ```print(*[i for i in room.boxes])``` you'll see the problem – Nin17 Jul 25 '22 at 05:39
  • `print(room.boxes[0])` here you are printing only 0th index value. That 0 should be dynamic if you want to list all boxes. – Bipin Maharjan Jul 25 '22 at 05:42
  • @Nin17 Thank you! Somehow I wasn't aware I was making a class-wide value when I intended to make an instance specific value. Dunno how I messed that up – YangTegap Jul 25 '22 at 05:51

1 Answers1

1
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.

ACE Fly
  • 305
  • 2
  • 8