str()
And repr()
¶
Stringification And Representation¶
str(obj)
: nicely made-up string, used by e.g.print()
repr(obj)
: object representation, ideally suitable aseval()
inputDefault: prints something useless (class name and object identity)
class Person: def __init__(self, firstname, lastname): self.firstname = firstname self.lastname = lastname person = Person('Joerg', 'Faschingbauer')
Expicitly calling
str()
on objectstr(person)
'<__main__.Person object at 0x7fb8d5c27d70>'
Using
print()
with an object callsstr()
on is ownprint(person)
<__main__.Person object at 0x7fb8d5c27d70>
repr()
on an objectrepr(person)
'<__main__.Person object at 0x7fb8d5c27d70>'
print()
a list of objects ⟶ usesrepr()
on list elementsprint([person])
[<__main__.Person object at 0x7fb8d5c27d70>]
Overloading str()
And repr()
: __str__()
, __repr__()
¶
__str__()
: returns human readable string, describing the object. Called, for example, byprint()
.__repr__()
: object representation. Usually the code to re-construct the object.class Person: def __init__(self, firstname, lastname): self.firstname = firstname self.lastname = lastname def __str__(self): return f'{self.firstname} {self.lastname}' def __repr__(self): return f'Person("{self.firstname}", "{self.lastname}")'
person = Person('Joerg', 'Faschingbauer')
str()
(andprint()
)str(person)
'Joerg Faschingbauer'
print(person)
Joerg Faschingbauer
repr()
(andprint()
on lists)print(repr(person))
Person("Joerg", "Faschingbauer")
print([person])
[Person("Joerg", "Faschingbauer")]