r/PythonLearning • • 28d ago

Why is my inventory class setup throwing errors? I'm super confused about how to use classes and instances here. 💀

Post image

Hey everyone! I'm trying to hack together a basic inventory and shop system for a little text-based game project I'm working on in Python, but I've totally tangled myself up in how classes, instances, and nested classes work.

I wanted to have a main game class that handles player info, and an inventory class nested inside (or attached to it) so the player can pick up items and check what's in their bag. But my code is completely throwing a fit.

10 Upvotes

6 comments sorted by

•

u/Sea-Ad7805 28d ago

Do it this way:

Run program above by clicking Memory Graph Web Debugger and see its state change step by step.

→ More replies (1)

4

u/grybyx 28d ago

Without seeing the exact errors, it’s difficult to assist. However, there are some obvious issues. Here are a few suggestions:

  1. Use PascalCase for class names. Your classes should be named Game and Inv.

  2. In general, don’t nest classes. It’s usually unnecessary. Move Inv out of Game. I think you’re trying to represent here that a Game object has an Inv object, which you’ll have after applying suggestion #3.

  3. Change line 48 to

self.inventory = Inv()

This calls the constructor for Inv and assigns the object to the game’s inventory attribute.

4. Change the rest of the program to:

game = Game(“someuser”)
game.inventory.add(“gun”)
game.inventory.show()

This should clear up a few of the errors.

2

u/ameeeeneeeeee 28d ago

Thank you; this fixed the error. Next time I will post the error too

1

u/NiedsoLake 23d ago edited 23d ago

On the class names, one other suggestion I’d make is to use descriptive names rather than abbreviations, i.e. “Inventory” instead of “Inv”. If you’re curious to learn more about why, I’d recommend this video: https://youtu.be/-J3wNP6u5YU?is=c_1U_wqw-OgkH0lu

Edit: this also looks like a great opportunity to learn about dependency injection. If you make Game.__init__ accept an Inventory instance as an argument to set self.inventory rather than constructing one itself, it’ll make it easier to extend or test in the future because then you can define different types of inventory that define the same methods but implement different behaviors. The same channel has a great video on this topic: https://youtu.be/J1f5b4vcxCQ?is=cml9vofwLhG6HEJb

1

u/Doctor_Disaster 28d ago

Can you post the traceback please?