tags:

views:

258

answers:

5

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?

+5  A: 

Checkout the __str__() and __repr__() methods.

See http://docs.python.org/reference/datamodel.html#object.__repr__

Peter Rowell
+1 for pointing __repr__.
nosklo
+4  A: 

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

class Foo:
    def __str__(self):
        return "String representation of me"
Dana
+8  A: 

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
Adam Rosenfield
+2  A: 

You need to override either the __str__, or __repr__ methods of your object[s]

cddr
A: 

My preference is to define a __repr__ function that can reconstruct the object (whenever possible). Unless you have a __str__ as well, both repr() and str() will call this method.

So for example

class Foo(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b
    def __repr__(self):
        return 'Foo(%r, %r)' % (self.a, self.b)

Doing it this way, you have a readable string version, and as a bonus it can be eval'ed to get a copy of the original object.

x = Foo(5, 1 + 1)
y = eval(str(x))

print y
-> Foo(5, 2)
Paul Hankin