[Python] Why does adding objects to global lists work during object initialization, but not...

Discussão em 'Python' iniciado por Stack, Abril 10, 2025.

  1. Stack

    Stack Membro Participativo

    I'm writing a very simple text-based escape game to practice the basics I've learned so far. I'm just running it in an online editor. I was having trouble adding class objects to a global list and learned that it was because I was initializing the objects, then adding them to the list afterward. After rewriting so that the objects got added to the list during their initialization, it worked. Why? (The game isn't done yet as you'll see, I just want a grip on what's happening before I continue.)

    ORIGINAL, NOT WORKING:

    class items():
    def __init__(self, item, canOpen):
    self.item = item
    self.canOpen = canOpen

    def pickup():
    choice = input(f"There's some stuff on this shelf: {freeItems} - What will you pick up?")
    #When freeItems is called, it displays [<__main__.items object at 0x7f4fbf4e08b0>, <__main__.items object at 0x7f4fbf4b3f70>]
    if choice not in freeItems:
    print(f"What? There's no {choice} here. Choose again.")
    #This runs no matter what I input, presumably because of the calling issue.
    choice = input()
    else:
    playerInventory.append(choice)
    freeItems.remove(choice)
    print(f"""{choice} added to inventory!
    These items remain on the shelf: {freeItems}
    Let's try opening the door.""")



    key = items("key",True)
    flashlight = items("flashlight",False)
    mirror = items("mirror",False)

    freeItems = [key, flashlight, mirror]
    playerInventory = []

    playerName = input("Hi there! What's your name?")
    print(f"Hi, {playerName}. So, bad news: you're trapped in this room. Good news: Your trusty disembodied narrator is here to help!")

    pickup()


    NEW, WORKING:

    freeItems = []
    playerInventory = []

    class items():
    def __init__(self, item, canOpen):
    self.item = item
    self.canOpen = canOpen
    freeItems.append(self.item) #This is the new code that made it work

    def pickup():
    choice = input(f"There's some stuff on this shelf: {freeItems} - What will you pick up?")
    if choice not in freeItems:
    print(f"What? There's no {choice} here. Choose again.")
    choice = input()
    else:
    playerInventory.append(choice)
    freeItems.remove(choice)
    print(f"""{choice} added to inventory!
    These items remain on the shelf: {freeItems}
    Let's try opening the door.""")



    key = items("key",True)
    flashlight = items("flashlight",False)
    mirror = items("mirror",False)

    playerName = input("Hi there! What's your name?")
    print(f"Hi, {playerName}. So, bad news: you're trapped in this room. Good news: Your trusty disembodied narrator is here to help!")

    pickup()


    In the original code, I tried adding existing class objects to a global list. I expected the objects to just be in the list as if I had added a normal variable to it. What actually happened is this output when the list was called: [<main.items object at 0x7f4fbf4e08b0>, <main.items object at 0x7f4fbf4b3f70>] and I subsequently couldn't use the list for the intended purpose.

    In the new code, I added the objects to the list as part of their initialization. This worked as intended. I just don't understand what the difference was to the program.

    Continue reading...

Compartilhe esta Página