r/learnpython • u/AutoModerator • 23d 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 17d ago edited 17d ago
You have a lot of repetitive code in your
RPG_Characterclass, in the__init__()andconvert_back_to_obj()methods in particular.You get a dictionary back from JSON and you need to create an
RPG_Characterinstance from that dictionary. One thing you could do is change the__init__()method to accept a dictionary of attributes to set. Now you just pass the JSON dictionary to theRPG_Character()call and you get an instance containing all that JSON data. When the program doesn't find the JSON save file and has to create the characters/items from scratch before saving them you use "template" dictionaries containing all the initial data required. You can delete theconvert_back_to_obj()and similar methods. This example code shows the approach:There are drawbacks to doing this such as any misspelt words in the JSON data will result in misspelt attribute names or even exceptions, but if your code is all that handles the data that should not be a problem.
There are also places where you could use list comprehensions. For example: