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
#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


Messages In This Thread
RE: Help with lists and class objects - by stullis - Jan-13-2020, 06:57 PM
RE: Help with lists and class objects - by buran - Jan-13-2020, 07:36 PM
RE: Help with lists and class objects - by snippsat - Jan-13-2020, 08:47 PM
RE: Help with lists and class objects - by stullis - Jan-14-2020, 11:25 PM
RE: Help with lists and class objects - by snippsat - Jan-15-2020, 12:48 PM

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,183 Aug-05-2023, 08:13 PM
Last Post: Konstantin23
  Creating list of lists, with objects from lists sgrinderud 7 1,817 Oct-01-2022, 07:15 PM
Last Post: Skaperen
  Split dict of lists into smaller dicts of lists. pcs3rd 3 2,554 Sep-19-2020, 09:12 AM
Last Post: ibreeden
  Class objects Python_User 12 4,689 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,148 Aug-14-2020, 12:37 PM
Last Post: Yoriz
  printing class properties from numpy.ndarrays of objects pjfarley3 2 2,047 Jun-08-2020, 05:30 AM
Last Post: pjfarley3
  How to serialize custom class objects in JSON? Exsul1 4 3,626 Sep-23-2019, 08:27 AM
Last Post: wavic
  How do I write class objects to a file in binary mode? Exsul1 7 6,001 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,454 Mar-20-2019, 08:01 PM
Last Post: stillsen
  Do objects get their own copy of the class methods? Charles1 1 2,165 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