851

When I try to print an instance of a class, I get an output like this:

>>> class Test():
... def __init__(self):
... self.a = 'foo'
...
>>> print(Test())
<__main__.Test object at 0x7fc9a9e36d60>

How can I make it so that the print will show something custom (e.g. something that includes the a attribute value)? That is, how can I can define how the instances of the class will appear when printed (their string representation)?


See How can I choose a custom string representation for a class itself (not instances of the class)? if you want to define the behaviour for the class itself (in this case, so that print(Test) shows something custom, rather than <class __main__.Test> or similar). (In fact, the technique is essentially the same, but trickier to apply.)

Karl Knechtel
61.4k14 gold badges131 silver badges193 bronze badges
asked Oct 8, 2009 at 2:35
0

13 Answers 13

964
>>> class Test:
... def __repr__(self):
... return "Test()"
... def __str__(self):
... return "member of Test"
... 
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test

The __str__ method is what gets called happens when you print it, and the __repr__ method is what happens when you use the repr() function (or when you look at it with the interactive prompt).

If no __str__ method is given, Python will print the result of __repr__ instead. If you define __str__ but not __repr__, Python will use what you see above as the __repr__, but still use __str__ for printing.

answered Oct 8, 2009 at 2:39
Sign up to request clarification or add additional context in comments.

7 Comments

there's also a unicode method, which you can use instead of Str ; note that it should return a unicode object, not a string (but if you return a string, the conversion to unicode will be done anyway...)
@kender - I didn't know about it, but in retrospect it makes perfect sense given Python 2.x's broken Unicode handling.
I think this answer cannot be completed without a link to this other one!
To Java programmers: __str__(self) is like the toString() of the python world
What if you can't edit the class you want to get information about?.. like something in a shared library / plugin? Surely there must be some kind of generic class method reflection available that doesn't require config?
|
192

As Chris Lutz explains, this is defined by the __repr__ method in your class.

From the documentation of repr():

For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.

Given the following class Test:

class Test:
 def __init__(self, a, b):
 self.a = a
 self.b = b
 def __repr__(self):
 return f"<Test a:{self.a} b:{self.b}>"
 def __str__(self):
 return f"From str method of Test: a is {self.a}, b is {self.b}"

..it will act the following way in the Python shell:

>>> t = Test(123, 456)
>>> t
<Test a:123 b:456>
>>> print(repr(t))
<Test a:123 b:456>
>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456

If no __str__ method is defined, print(t) (or print(str(t))) will use the result of __repr__ instead

If no __repr__ method is defined then the default is used, which is roughly equivalent to:

def __repr__(self):
 cls = self.__class__
 return f"<{cls.__module_}.{cls.__qualname__} object at {id(self)}>"
Karl Knechtel
61.4k14 gold badges131 silver badges193 bronze badges
answered Oct 8, 2009 at 2:55

7 Comments

+1 but your class code's __str__ is different from the interactive shell's results you give. :P
Err, oops.. manually modifying REPL output never ends well. I should probably doctest my posts :P
The % string formatting isn't deprecated, from docs.python.org/whatsnew/2.6.html "the % operator is supplemented by a more powerful string formatting method, format()"
Dbr: That is true. Do note that the "What's New In Python 3.0" doc also says "format() method [...] The plan is to eventually make this the only API for string formatting, and to start deprecating the % operator in Python 3.1."
Pitty, %'s been very convenient.
|
132

If you're in a situation like @Keith you could try:

print(a.__dict__)

It goes against what I would consider good style but if you're just trying to debug then it should do what you want.

answered Oct 25, 2018 at 22:25

6 Comments

Would you know how to know if the dict key has objects in its values?
@HadoopEvangelist Are you asking how to recursively print those objects as well or just determine if there are objects?
This is one of the best answers out there when it comes to a quick debug. Thanks @John
Essentially the same as stackoverflow.com/a/32635523/2707864
print(self.__dict__) works as well. Specially useful when debugging the code without __repr__ and __str__ are defined by the class author.
|
85

A generic way that can be applied to any class without specific formatting could be done as follows:

class Element:
 def __init__(self, name, symbol, number):
 self.name = name
 self.symbol = symbol
 self.number = number
 def __str__(self):
 return str(self.__class__) + ": " + str(self.__dict__)

And then,

elem = Element('my_name', 'some_symbol', 3)
print(elem)

produces

__main__.Element: {'symbol': 'some_symbol', 'name': 'my_name', 'number': 3}
answered Sep 17, 2015 at 16:35

Comments

22

Simple. In the print, do:

print(foobar.__dict__)

as long as the constructor is

__init__
answered Jan 27, 2021 at 17:01

1 Comment

Partially interesting. It's fast and "builtin" but is limited to basic value type. A new class object inside will display the class type not the content. So helpfull and interesting too use but not exhaustive compare to the request like str_ and repr do.
21

A prettier version of response by @user394430

class Element:
 def __init__(self, name, symbol, number):
 self.name = name
 self.symbol = symbol
 self.number = number
 def __str__(self):
 return str(self.__class__) + '\n'+ '\n'.join(('{} = {}'.format(item, self.__dict__[item]) for item in self.__dict__))
elem = Element('my_name', 'some_symbol', 3)
print(elem)

Produces visually nice list of the names and values.

<class '__main__.Element'>
name = my_name
symbol = some_symbol
number = 3

An even fancier version (thanks Ruud) sorts the items:

def __str__(self):
 return str(self.__class__) + '\n' + '\n'.join((str(item) + ' = ' + str(self.__dict__[item]) for item in sorted(self.__dict__)))
answered Mar 14, 2018 at 15:44

1 Comment

return ','.join(('{} = {}'.format(item, self.__dict__[item]) for item in self.__dict__)) .........puts everyting on one line. I removed the class name, I just wanted to print the values for purpose of debugging
17

For Python 3:

If the specific format isn't important (e.g. for debugging) just inherit from the Printable class below. No need to write code for every object.

Inspired by this answer

class Printable:
 def __repr__(self):
 from pprint import pformat
 return "<" + type(self).__name__ + "> " + pformat(vars(self), indent=4, width=1)
# Example Usage
class MyClass(Printable):
 pass
my_obj = MyClass()
my_obj.msg = "Hello"
my_obj.number = "46"
print(my_obj)
answered May 20, 2016 at 14:26

2 Comments

this looks funky when values have spaces...
print(vars(obj)) -> good enough for me, thanks
14

Just to add my two cents to @dbr's answer, following is an example of how to implement this sentence from the official documentation he's cited:

"[...] to return a string that would yield an object with the same value when passed to eval(), [...]"

Given this class definition:

class Test(object):
 def __init__(self, a, b):
 self._a = a
 self._b = b
 def __str__(self):
 return "An instance of class Test with state: a=%s b=%s" % (self._a, self._b)
 def __repr__(self):
 return 'Test("%s","%s")' % (self._a, self._b)

Now, is easy to serialize instance of Test class:

x = Test('hello', 'world')
print 'Human readable: ', str(x)
print 'Object representation: ', repr(x)
print
y = eval(repr(x))
print 'Human readable: ', str(y)
print 'Object representation: ', repr(y)
print

So, running last piece of code, we'll get:

Human readable: An instance of class Test with state: a=hello b=world
Object representation: Test("hello","world")
Human readable: An instance of class Test with state: a=hello b=world
Object representation: Test("hello","world")

But, as I said in my last comment: more info is just here!

answered Dec 20, 2012 at 11:27

Comments

12

You need to use __repr__. This is a standard function like __init__. For example:

class Foobar():
 """This will create Foobar type object."""
 def __init__(self):
 print "Foobar object is created."
 def __repr__(self):
 return "Type what do you want to see here."
a = Foobar()
print a
Robφ
170k20 gold badges251 silver badges323 bronze badges
answered Jan 16, 2013 at 9:04

1 Comment

repr and str have different semantics: repr should be Python source that would (re-)create the same object -- this is its representation in code ; str should be a pretty userland stringification of the object.
9

__repr__ and __str__ are already mentioned in many answers. I just want to add that if you are too lazy to add these magic functions to your class, you can use objprint. A simple decorator @add_objprint will help you add the __str__ method to your class and you can use print for the instance. Of course if you like, you can also use objprint function from the library to print any arbitrary objects in human readable format.

from objprint import add_objprint
class Position:
 def __init__(self, x, y):
 self.x = x
 self.y = y
@add_objprint
class Player:
 def __init__(self):
 self.name = "Alice"
 self.age = 18
 self.items = ["axe", "armor"]
 self.coins = {"gold": 1, "silver": 33, "bronze": 57}
 self.position = Position(3, 5)
print(Player())

The output is like

<Player
 .name = 'Alice',
 .age = 18,
 .items = ['axe', 'armor'],
 .coins = {'gold': 1, 'silver': 33, 'bronze': 57},
 .position = <Position
 .x = 3,
 .y = 5
 >
>
answered Mar 13, 2021 at 0:59

Comments

7

Even though this is an older post, there is also a very convenient method introduced in dataclasses (as of Python 3.7). Besides other special functions such as __eq__ and __hash__, it provides a __repr__ function for class attributes. You example would then be:

from dataclasses import dataclass, field
@dataclass
class Test:
 a: str = field(default="foo")
 b: str = field(default="bar")
t = Test()
print(t) 
# prints Test(a='foo', b='bar')

If you want to hide a certain attribute from being outputted, you can set the field decorator parameter repr to False:

@dataclass
class Test:
 a: str = field(default="foo")
 b: str = field(default="bar", repr=False)
t = Test()
print(t) 
# prints Test(a='foo')
answered Aug 24, 2022 at 14:54

Comments

1

There are already a lot of answers in this thread but none of them particularly helped me, I had to work it out myself, so I hope this one is a little more informative.

You just have to make sure you have parentheses at the end of your class, e.g:

print(class())

Here's an example of code from a project I was working on:

class Element:
 def __init__(self, name, symbol, number):
 self.name = name
 self.symbol = symbol
 self.number = number
 def __str__(self):
 return "{}: {}\nAtomic Number: {}\n".format(self.name, self.symbol, self.number
class Hydrogen(Element):
 def __init__(self):
 super().__init__(name = "Hydrogen", symbol = "H", number = "1")

To print my Hydrogen class, I used the following:

print(Hydrogen())

Please note, this will not work without the parentheses at the end of Hydrogen. They are necessary.

Hope this helps, let me know if you have anymore questions.

answered Aug 4, 2015 at 4:52

Comments

-1

None of the above answers helped me. In my case, I had to make sure there were parentheses at the end of myr class, e.g.:

print(class())

Here's an example of code from a project I was working on:

class Element:
 def __init__(self, name, symbol, number):
 self.name = name
 self.symbol = symbol
 self.number = number
 def __str__(self):
 return "{}: {}\nAtomic Number: {}\n".format(self.name, self.symbol, self.number
class Hydrogen(Element):
 def __init__(self):
 super().__init__(name = "Hydrogen", symbol = "H", number = "1")
L Tyrone
8,35123 gold badges34 silver badges47 bronze badges
answered Aug 12, 2024 at 9:54

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.