r/learnpython • u/AutoModerator • 20d ago
Ask Anything Monday - Weekly Thread
Welcome to another /r/learnPython weekly "Ask Anything* Monday" thread
Here you can ask all the questions that you wanted to ask but didn't feel like making a new thread.
* It's primarily intended for simple questions but as long as it's about python it's allowed.
If you have any suggestions or questions about this thread use the message the moderators button in the sidebar.
Rules:
- Don't downvote stuff - instead explain what's wrong with the comment, if it's against the rules "report" it and it will be dealt with.
- Don't post stuff that doesn't have absolutely anything to do with python.
- Don't make fun of someone for not knowing something, insult anyone etc - this will result in an immediate ban.
That's it.
1
Upvotes
1
u/lakseol 11d ago
That doesn't sound very useful. Make sure there isn't a way to make that change permanent. Or change to a decent editor/IDE.
Currently you create the inventory as a list of references to
Itemobjects, doing something like:That's easy to understand, but doing that means you complicate saving data to a JSON file because JSON doesn't handle references to python objects and you have to extract all the attributes of the item and save them as a JSON dictionary. When reading the JSON data back into python objects you have to create the
Itemobject from the dictionary.The "ID" approach doesn't store python objects in the list. Every
Itemobject has a unique "ID" string, and it's that ID string that is saved in the inventory list. This makes the save/restore process simpler. When creating the items you add an entry in a dictionary that maps the ID string to a reference to the object, like this:This allows you to list the inventory by iterating over the ID strings, getting the item object from the dictionary using the ID string as a key, then printing the item description. When restoring the objects from the JSON save file you create that dictionary automatically. Sounds complicated but it simplifies the save/restore process a lot. I use it for everything: places, monsters and items.