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.)
>>> 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.
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)}>"
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.
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}
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__)))
Simple. In the print, do:
print(foobar.__dict__)
as long as the constructor is
__init__
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)
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!
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
__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
>
>
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.
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')
Related
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.)
>>> 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.
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)}>"
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.
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}
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__)))
Simple. In the print, do:
print(foobar.__dict__)
as long as the constructor is
__init__
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)
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!
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
__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
>
>
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.
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')
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.)
>>> 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.
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)}>"
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.
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}
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__)))
Simple. In the print, do:
print(foobar.__dict__)
as long as the constructor is
__init__
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)
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!
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
__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
>
>
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.
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')
I'm trying to make an array of class objects. When I create the object, it works great:
class Complex(object):
def __init__(self, realpart, imagpart):
#creates complex number
self.r = realpart
self.i = imagpart
def __str__(self):
'''Returns complex number as a string'''
return '(%s + %s j)' % (self.r, self.i)
a = Complex(1,0)
print a
(1 + 0 j)
But when I try to put a in an array, I get an error:
arr1 = [a]
[<__ main __.Complex object at 0x5afab0>]
Why could this be happening? Thanks in advance.
Because __repr__ was used instead of __str__. Override __repr__ as Ashwini Chaudhary commented.
>>> class Complex(object):
... def __init__(self, realpart, imagpart):
... self.r = realpart
... self.i = imagpart
... def __str__(self):
... '''Returns complex number as a string'''
... return '(%s + %s j)' % (self.r, self.i)
... __repr__ = __str__ # <-----
...
>>> a = Complex(1,0)
>>> [a]
[(1 + 0 j)]
As per the docs, print normally calls __str__, so when you printed the object, __str__ is invoked. But when you print the builtin collections, the __str__ method of them invoke __iter__ of the individual elements in it. So, your must implement __iter__ on your own, or let the default __repr__ as it is.
If you decide to implement __repr__ yourself, the docs say,
If at all possible, this should look like a valid Python expression
that could be used to recreate an object with the same value (given an
appropriate environment). If this is not possible, a string of the
form <...some useful description...> should be returned. The return
value must be a string object.
So, if you are implementing it yourself, give as much information as possible, so that the __repr__ output is unambiguous and useful for debugging.
def __str__(self):
'''Returns complex number as a string'''
return '< Complex({} + {}j) >'.format(self.r, self.i)
You can read more about this, in this answer.
This question already has answers here:
What is the difference between __str__ and __repr__?
(28 answers)
Closed 2 years ago.
I really don't understand where are __str__ and __repr__ used in Python. I mean, I get that __str__ returns the string representation of an object. But why would I need that? In what use case scenario? Also, I read about the usage of __repr__
But what I don't understand is, where would I use them?
__repr__
Called by the repr() built-in function and by string conversions (reverse quotes) to compute the "official" string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment).
__str__
Called by the str() built-in function and by the print statement to compute the "informal" string representation of an object.
Use __str__ if you have a class, and you'll want an informative/informal output, whenever you use this object as part of string. E.g. you can define __str__ methods for Django models, which then gets rendered in the Django administration interface. Instead of something like <Model object> you'll get like first and last name of a person, the name and date of an event, etc.
__repr__ and __str__ are similar, in fact sometimes equal (Example from BaseSet class in sets.py from the standard library):
def __repr__(self):
"""Return string representation of a set.
This looks like 'Set([<list of elements>])'.
"""
return self._repr()
# __str__ is the same as __repr__
__str__ = __repr__
The one place where you use them both a lot is in an interactive session. If you print an object then its __str__ method will get called, whereas if you just use an object by itself then its __repr__ is shown:
>>> from decimal import Decimal
>>> a = Decimal(1.25)
>>> print(a)
1.25 <---- this is from __str__
>>> a
Decimal('1.25') <---- this is from __repr__
The __str__ is intended to be as human-readable as possible, whereas the __repr__ should aim to be something that could be used to recreate the object, although it often won't be exactly how it was created, as in this case.
It's also not unusual for both __str__ and __repr__ to return the same value (certainly for built-in types).
Building up and on the previous answers and showing some more examples. If used properly, the difference between str and repr is clear. In short repr should return a string that can be copy-pasted to rebuilt the exact state of the object, whereas str is useful for logging and observing debugging results. Here are some examples to see the different outputs for some known libraries.
Datetime
print repr(datetime.now()) #datetime.datetime(2017, 12, 12, 18, 49, 27, 134411)
print str(datetime.now()) #2017-12-12 18:49:27.134452
The str is good to print into a log file, where as repr can be re-purposed if you want to run it directly or dump it as commands into a file.
x = datetime.datetime(2017, 12, 12, 18, 49, 27, 134411)
Numpy
print repr(np.array([1,2,3,4,5])) #array([1, 2, 3, 4, 5])
print str(np.array([1,2,3,4,5])) #[1 2 3 4 5]
in Numpy the repr is again directly consumable.
Custom Vector3 example
class Vector3(object):
def __init__(self, args):
self.x = args[0]
self.y = args[1]
self.z = args[2]
def __str__(self):
return "x: {0}, y: {1}, z: {2}".format(self.x, self.y, self.z)
def __repr__(self):
return "Vector3([{0},{1},{2}])".format(self.x, self.y, self.z)
In this example, repr returns again a string that can be directly consumed/executed, whereas str is more useful as a debug output.
v = Vector3([1,2,3])
print str(v) #x: 1, y: 2, z: 3
print repr(v) #Vector3([1,2,3])
One thing to keep in mind, if str isn't defined but repr, str will automatically call repr. So, it's always good to at least define repr
Grasshopper, when in doubt go to the mountain and read the Ancient Texts. In them you will find that __repr__() should:
If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value.
Lets have a class without __str__ function.
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
emp1 = Employee('Ivan', 'Smith', 90000)
print(emp1)
When we print this instance of the class, emp1, this is what we get:
<__main__.Employee object at 0x7ff6fc0a0e48>
This is not very helpful, and certainly this is not what we want printed if we are using it to display (like in html)
So now, the same class, but with __str__ function:
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
def __str__(self):
return(f"The employee {self.first} {self.last} earns {self.pay}.")
# you can edit this and use any attributes of the class
emp2 = Employee('John', 'Williams', 90000)
print(emp2)
Now instead of printing that there is an object, we get what we specified with return of __str__ function:
The employee John Williams earns 90000
str will be informal and readable format whereas repr will give official object representation.
class Complex:
# Constructor
def __init__(self, real, imag):
self.real = real
self.imag = imag
# "official" string representation of an object
def __repr__(self):
return 'Rational(%s, %s)' % (self.real, self.imag)
# "informal" string representation of an object (readable)
def __str__(self):
return '%s + i%s' % (self.real, self.imag)
t = Complex(10, 20)
print (t) # this is usual way we print the object
print (str(t)) # this is str representation of object
print (repr(t)) # this is repr representation of object
Answers :
Rational(10, 20) # usual representation
10 + i20 # str representation
Rational(10, 20) # repr representation
str and repr are both ways to represent. You can use them when you are writing a class.
class Fraction:
def __init__(self, n, d):
self.n = n
self.d = d
def __repr__(self):
return "{}/{}".format(self.n, self.d)
for example when I print a instance of it, it returns things.
print(Fraction(1, 2))
results in
1/2
while
class Fraction:
def __init__(self, n, d):
self.n = n
self.d = d
def __str__(self):
return "{}/{}".format(self.n, self.d)
print(Fraction(1, 2))
also results in
1/2
But what if you write both of them, which one does python use?
class Fraction:
def __init__(self, n, d):
self.n = n
self.d = d
def __str__(self):
return "str"
def __repr__(self):
return "repr"
print(Fraction(None, None))
This results in
str
So python actually uses the str method not the repr method when both are written.
Suppose you have a class and wish to inspect an instance, you see the print doesn't give much useful information
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1) # <__main__.Animal object at 0x7f9060250410>
Now see a class with a str, it shows the instance information and with repr you even don't need the print. Nice no?
class Animal:
def __init__(self, color, age, breed):
self.color = color
self.age = age
self.breed = breed
def __str__(self):
return f"{self.color} {self.breed} of age {self.age}"
def __repr__(self):
return f"repr : {self.color} {self.breed} of age {self.age}"
a1 = Animal("Red", 36, "Dog")
a1 # repr : Red Dog of age 36
print(a1) # Red Dog of age 36
Suppose one decided (yes, this is horrible) to create handle input in the following manner: A user types in a command on the python console after importing your class, the command is actually a class name, the class name's __str__ function is actually a function with side effects (e.g. the command is "north" and the function changes some global variables and then returns text describing your current location). Obviously this is a stupid thing to do, but how would you do it (if possible)?
Note that the basic question is how to define the __str__ method for a class without creating an instance of the class, otherwise it would be simple (but still just as crazy:
class ff:
def __str__(self):
#do fun side effects
return "fun text string"
ginst = ff()
>>ginst
What you are looking for is the metaclass
class Magic(type):
def __str__(self):
return 'Something crazy'
def __repr__(self):
return 'Another craziness'
class Foo(object):
__metaclass__ = Magic
>>> print Foo
Something crazy
>>> Foo
Another craziness
in console you're getting representation of your object, which __repr__ is responsible for. __str__ used for printing:
>>> class A:
def __str__(self):
return 'spam'
>>> A()
<__main__.A object at 0x0107E3D0>
>>> print(A())
spam
>>> class B:
def __repr__(self):
return 'ham'
>>> B()
ham
>>> print(B())
ham
>>> class C:
def __str__(self):
return 'spam'
def __repr__(self):
return 'ham'
>>> C()
ham
>>> print(C())
spam
You could use instances of a class rather than classes themselves. Something like
class MagicConsole(object):
def __init__(self, f):
self.__f = f
def __repr__(self):
return self.__f()
north = MagicConsole(some_function_for_north)
south = MagicConsole(some_function_for_south)
# etc