1

I'm learning python and started a card game to gain OOP experience. I simplified my code below for demonstration purposes. It is showing behavior that I did not at all expect.

class Room:
    def __init__(self, things=[]):
        self.things = things
        for i in range(20):
            self.things += [Thing(i)]

    def move(self, *args):
        for arg in args:
            arg.things += [self.things[0]]
            self.things = self.things[1:]

    def display(self):
        print('Room contents:')
        for thing in self.things:
            print(thing.num)

class Thing:
    def __init__(self, num):
        self.num = num

class Box:
    def __init__(self, name, things=[]):
        self.name = name
        self.things = things

    def look_inside(self):
        print('Contents of box', self.name, ':')
        for thing in self.things:
            print(thing.num)
        print()

room = Room()

box1 = Box('Box 1')
box2 = Box('Box 2')
box3 = Box('Box 3')
box4 = Box('Box 4')

room.move(box1, box2)

box1.look_inside()
box2.look_inside()
box3.look_inside()
box4.look_inside()

Output:

Contents of box Box 1

0

1

Contents of box Box 2

0

1

Contents of box Box 3

0

1

Contents of box Box 4

0

1

  • The method room.move(box1, box2) seems to operate on box3 and box4 even though they aren't passed as arguments.
  • I expected the method room.move would cycle through box1 and box2 as a tuple. So calling room.move(box1, box2) would move the first two things, one each into box1 and box2. But each time through the for loop seems to move a copy of the thing into each box (1 though 4).

Why does room.move affect box3 and box4 and how can I make it only operate on the Boxes I pass to it?

Why does the for loop in room.move perform the operation on all the Boxes instead of only the Box that is arg for that iteration through the loop?

When I look for information about how *args works, I can only find instruction about passing strings, integers, etc. I can't find anything that speaks to passing custom classes. I can only suspect that my problem is in understanding how this works. Can anybody recommend further reading or a tutorial on this specific case?

Thank you.

Dan
  • 11
  • 3

0 Answers0