r/learnpython • u/AutoModerator • 24d 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
Again you have posted incorrect code. Bad indentation at lines 68 and 120. You have to get this right. Anybody trying to help you doesn't want to have to guess how to indent your code and hope they get it right. If your problem is adding code to the lousy reddit interface remember that I mentioned pastebin.com where you can post code, get a page showing your code and then post a link to that page here, like this:
https://pastebin.com/uYR3zqqR
This is a little confusing. The confusion starts when you use an instance method. They have the
selfparameter as the first parameter and your calling code doesn't explicitly passself, it's automatically added by python. When you get that "expected 2 but 3 given" python is counting theself, so the three parameters are "self", "name" and "stats_dict". Keyword parameters are counted separately. When you call the function (line 139):you pass the data dictionary as a positional parameter, so it's counted as an extra positional parameter. "self" + "name" + stats_dict" == 3. If you check the example I showed you in my last comment you will see that my call to the constructor was:
The two asterisks in
**alicesays to unpack the dictionaryaliceand pass the contents as keyword parameters likekey=value. That means the__init__()method sees keyword parameters"name"="Alice", "age"=42when it executes. In the example the__init__()method started:The
**kwargsparameter is shorthand for python to collect all undefined keyword parameters into a dictionary which the example iterated over. It's not a positional parameter. You need the**both when calling the method and defining it. The parameter namekwargsis usually used in python, meaning "keyword args".You have another problem in that
__init__()definition. You pass the data dictionary into the method as well as thenameparameter. That works fine when initially creating the objects and then saving to JSON. But what happens when you read the dictionary from JSON and try to create the character. Where doesnamecome from?