Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Same Python object created on each iteration

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()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading