That's the beauty of over-riding the magic methods (also called "dunders" for double underscores). You don't have to do anything else. Any time your object gets printed, __str__ will get called and whatever you defined in it will be printed. See how when I "print(thing1)" it just works. Pretty useful!
I guess I should have mentioned that overriding __str__() and __repr__() is not the only way to print stuff from a class instance. As you see in my code I also added a fancy, multi-line show_item_info() method that simply prints lines that happen to contain several attributes from the class. Of course you can combine the techniques too. You could make a nice printout of all the items in the inventory as a pretty 2D table but leave out the descriptions...
class Items(): """ Base class of Player's items. """ inventory = [] # Static class attribute to hold all items. Note that it's IN the class. def list_items(): # Static method to print the items in the static inventory. for i in Items.inventory: print(i) def __init__(self, name, desc): """ Constructor for the Items class. """ self.name = name self.description = desc self.attack = 10 self.defense = 10 self.value = 25 Items.inventory.append(self) def __str__(self): return self.name def show_item_info(self): print("-----------------------------------------") print(f"Item name: {self.name}") print(self.description) print(f"Attack: {self.attack} / Defense: {self.defense}") print("-----------------------------------------") # Instantiate a couple items: thing1 = Items("Iron Sword", "A rusty iron short sword that badly needs a blacksmith.") thing2 = Items("Wooden Shield", "A tattered, oak shield that has seen better days but does the job.") # Print some output about the Items: print(thing1) # Just USE it. Works since you over-rode __str__ "magic method"! thing2.show_item_info() Items.list_items()
I guess I should have mentioned that overriding __str__() and __repr__() is not the only way to print stuff from a class instance. As you see in my code I also added a fancy, multi-line show_item_info() method that simply prints lines that happen to contain several attributes from the class. Of course you can combine the techniques too. You could make a nice printout of all the items in the inventory as a pretty 2D table but leave out the descriptions...
"So, brave knights, if you do doubt your courage or your strength, come no further, for death awaits you all with nasty, big, pointy teeth!" - Tim the Enchanter