chronocturnal
chronocturnal

Reputation: 3

Class object display 'class object at ...'

I'm wondering that when creating a class in python, for example, a class Car, with the attributes being the make and year of the car, can return the name and the make, without using anything except for

>>> c = Car('Toyota Camry', 2007)
>>> c

instead of returning <car object at 0x0000000003394FD0>

is there anyway to just return a tuple of

('Toyota Camry', 2007)

without implementing a __str__ method in the car class?

Upvotes: 0

Views: 246

Answers (2)

A.J. Uppal
A.J. Uppal

Reputation: 19264

Use __repr__ instead of __str__.

__repr__ represents the objuect, while __str__ is only called with a print().

To do that, use the following:

class Car:

    def __init__(self, model, year):
        self.model = model
        self.year = year

    def __repr__(self):
        return str((self.model, self.year))

This will run as:

>>> camry = Car('Toyota Camry', 2006)
>>> camry
('Toyota Camry', 2006)
>>> 

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1122372

You'd implement a __repr__ method; it is that method that is used when representing an object:

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

    def __repr__(self):
        return 'Car({!r}, {!r})'.format(self.make, self.year)

This produces a representation string that looks just like the original class invocation:

>>> class Car:
...     def __init__(self, make, year):
...         self.make = make
...         self.year = year
...     def __repr__(self):
...         return 'Car({!r}, {!r})'.format(self.make, self.year)
... 
>>> Car('Toyota Camry', 2007)
Car('Toyota Camry', 2007)

Upvotes: 3

Related Questions