Python Forum
Help with lists and class objects
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with lists and class objects
#1
So, I want to make an inventory system, if the user has an item, it puts it into a list called inventory. The item is an object inside a class, and if I put the object from the class into the inventory list and when I print out the inventory, I want to show up as the the items name.

inventory = []

class items():
    def __init__(self, item):
        self.item = item

sword = items('sword')
inventory.append(sword)

print(inventory)
I want it to print Sword, not [<__main__.items object at 0x7f36f0a8a750>]
hopefulle I explained this decently, I'm new to Python :)
Reply
#2
For that, you'll need to write some code for items.__repr__(). That dunder method is called whenever the object is printed.
Reply
#3
Sorry but I don't understand what __repr__() is, would you mind explaining? and how would I add that to my code?
Reply
#4
https://docs.python.org/3/reference/data...t.__repr__

check also

https://docs.python.org/3/reference/data...ct.__str__
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
(Jan-13-2020, 07:21 PM)AlluminumFoil Wrote: would you mind explaining? and how would I add that to my code?
inventory = []
class Items:
    def __init__(self, item):
        self.item = item

    def __str__(self):
        return f'The item is: {self.item}'

    def __repr__(self):
        return f'Items({self.item!r})'
Use:
>>> sword = Items('sword')
>>> 
>>> # Call __str__
>>> print(sword)
The item is: sword
>>> 
>>> # Call __repr__
>>> sword
Items('sword')
This is a standard way to use it.
__str__ here can add text that give more info about the object.
__repr__ Give raw info about object intended more as a aid for developers and debugging.
Reply
#6
Ok so the problem with that is that I have more than one one thing inside. for example, I don't have only 'item' inside the __init__, It looks more like this:

def __init__(self, item, attack, sell_price, buy_price)
So I want to make it that when I print the inventory list, it shows a list of the objects inside, not the attack, not the sellprice, etc. Only the item. I've been researching it and I cannot find anything about this at all.
Reply
#7
__str__ and __repr__ will still work. Just decide what you want to print. As you have been shown above you can define what attributes are printed:

def __str__(self):
return "self.item"  # will display just the name of the item.

def __str__(self):
return f"This item is a {self.item}. It attacks for {self.attack} damage!" # Displays a fancy message about item.
BTW, it's confusing to use "item" as the name of your Items. How about "name"?
"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
Reply
#8
and how would I call out the __str__? like I put that in my class,
def __str__(self):
    return f"self.item"
like when I want to append sword to the inventory list, and then print out what's above
Reply
#9
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!

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
Reply
#10
Hello again, unfortunately, I'm still having problems with this, I don't know what I'm doing wrong at this point, but would you or anyone be able to look over my code and see what I'm doing wrong?

Line 16 is where the class I'm working with at the moment, ignore the other classes, I'll work on those later.
Line 65 is all the objects for the class at Line 16.
Line 351 is where I'm attempting to print the inventory as a list.

I created a file in Github, i don't know if I set it up right, so here's the link anyways.
https://github.com/DankRupped/Crates/tree/master
Thank you guys for all the help
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How can I access objects or widgets from one class in another class? Konstantin23 3 1,011 Aug-05-2023, 08:13 PM
Last Post: Konstantin23
  Creating list of lists, with objects from lists sgrinderud 7 1,639 Oct-01-2022, 07:15 PM
Last Post: Skaperen
  Split dict of lists into smaller dicts of lists. pcs3rd 3 2,378 Sep-19-2020, 09:12 AM
Last Post: ibreeden
  Class objects Python_User 12 4,469 Aug-27-2020, 08:02 PM
Last Post: Python_User
  How to create and define in one line a 2D list of class objects in Python T2ioTD 1 2,041 Aug-14-2020, 12:37 PM
Last Post: Yoriz
  printing class properties from numpy.ndarrays of objects pjfarley3 2 1,956 Jun-08-2020, 05:30 AM
Last Post: pjfarley3
  How to serialize custom class objects in JSON? Exsul1 4 3,496 Sep-23-2019, 08:27 AM
Last Post: wavic
  How do I write class objects to a file in binary mode? Exsul1 7 5,760 Sep-14-2019, 09:33 PM
Last Post: snippsat
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 3,286 Mar-20-2019, 08:01 PM
Last Post: stillsen
  Do objects get their own copy of the class methods? Charles1 1 2,101 Feb-02-2019, 04:40 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020