GregH
GregH

Reputation: 12858

Outputting object in Python using print

I am instantiating a class and simply want to dump the object using print. When I do this I seem to get some sort of object id. Can't I just issue a "print ObjectName" and the result would just be the attributes of the object? Here is an example of what I am doing:

class Car:
    def __init__(self, color, make, model):
        self.color = color
        self.make = make
        self.model = model

    def getAll():
        return (self.color, self.make, self.model)


mycar = Car("white","Honda","Civic")
print mycar

When I run this I get the following result:

<__main__.Car instance at 0x2b650357be60>

I would expect to see the color,make,model values as well. I know if I print them individually via:

print mycar.color,mycar.make,mycar.model

It output:

white Honda Civic

Just as I would expect. Why does "print mycar" output an instance id and not the attribute values?

Upvotes: 2

Views: 170

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121246

Define a .__str__() method on your class. It'll be called when printing your custom class instances:

class Car:
    def __init__(self, color, make, model):
        self.color = color
        self.make = make
        self.model = model

    def __str__(self):
        return ' '.join((self.color, self.make, self.model))

Demo:

>>> mycar = Car("white","Honda","Civic")
>>> print mycar
white Honda Civic

In addition, you could implement a .__repr__() method too, to provide a debugger-friendly representation of your instances.

Upvotes: 3

manojlds
manojlds

Reputation: 301037

You need to implement __str__ and __repr__ to get "friendly" values for your class objects.

Look here for more details on this.

__repr__ is the official string represntation of an object and is called by repr() and __str__ is the informal string representation and is called by str()

Upvotes: 2

Related Questions