6. Stringify objects

6.1. __str__ vs. __repr__

6.1.1. __str__()

  • __str__() dla użytkowników (być czytelnym)

  • print converts it's arguments to str() before printing

Listing 275. Object without __str__() method overloaded prints their memory address
class Iris:
    def __init__(self, species):
        self.species = species


flower = Iris('setosa')

str(flower)       # <__main__.Iris object at 0x112b366d8>
print(flower)     # <__main__.Iris object at 0x112b366d8>
Listing 276. Objects can verbose print if __str__() method is present
class Iris:
    def __init__(self, species):
        self.species = species

    def __str__(self):
        return f'Species: {self.species}'


flower = Iris('setosa')

str(flower)       # Species: setosa
print(flower)     # Species: setosa

6.1.2. __repr__()

  • __repr__() jest dla developerów (być jednoznacznym)

Listing 277. Using __repr__() on a class
class Iris:
    def __init__(self, species):
        self.species = species

    def __repr__(self):
        return f'Iris(species="{self.species}")'


 flower = Iris(species='setosa')

 repr(point)    # Iris(species="setosa")
 point          # Iris(species="setosa")

6.1.3. Examples

Listing 278. __str__ and __repr__
import datetime

str(datetime.datetime.now())
# 2019-01-05 20:15:00.927387

repr(datetime.datetime.now())
# datetime.datetime(2019, 1, 5, 20, 15, 0, 684972)
Listing 279. printing list will call __repr__ on each element
class Astronaut:
    def __init__(self, name):
        self.name = name

crew = [
    Astronaut('Jan Twardowski'),
    Astronaut('Mark Watney'),
    Astronaut('Melissa Lewis'),
]

print(crew)
# [
#   <__main__.Astronaut object at 0x107871160>,
#   <__main__.Astronaut object at 0x107c422e8>,
#   <__main__.Astronaut object at 0x108156be0>
# ]
Listing 280. printing list will call __repr__ on each element
class Astronaut:
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return f'{self.name}'

crew = [
    Astronaut('Jan Twardowski'),
    Astronaut('Mark Watney'),
    Astronaut('Melissa Lewis'),
]

print(crew)
# [Jan Twardowski, Mark Watney, Melissa Lewis]