Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - readable list of objects

Tags:

python

list

This is probably a kinda commonly asked question but I could do with help on this. I have a list of class objects and I'm trying to figure out how to make it print an item from that class but rather than desplaying in the;

<__main__.evolutions instance at 0x01B8EA08>

but instead to show a selected attribute of a chosen object of the class. Can anyone help with that?

like image 869
user33061 Avatar asked Jan 14 '09 18:01

user33061


2 Answers

If you want to just display a particular attribute of each class instance, you can do

print([obj.attr for obj in my_list_of_objs])

Which will print out the attr attribute of each object in the list my_list_of_objs. Alternatively, you can define the __str__() method for your class, which specifies how to convert your objects into strings:

class evolutions:
    def __str__(self):
        # return string representation of self

print(my_list_of_objs)  # each object is now printed out according to its __str__() method
like image 64
Adam Rosenfield Avatar answered Oct 12 '22 06:10

Adam Rosenfield


You'll want to override your class's "to string" method:

class Foo:
    def __str__(self):
        return "String representation of me"
like image 27
Dana Avatar answered Oct 12 '22 07:10

Dana