16.16. OOP Stringify Str

  • Dedicated for end-user of your class

  • Calling function print(obj) calls str(obj)

  • Calling function str(obj) calls obj.__str__()

  • Calling f'{obj}' calls obj.__str__()

  • Calling f'{obj!s}' calls obj.__str__()

  • Method obj.__str__() must return str

16.16.1. Without Method

Object without __str__() method overloaded prints their memory address:

>>> class User:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
>>>
>>>
>>> mark = User('Mark', 'Watney')
>>> print(mark)  
<__main__.User object at 0x10aef7450>
>>> str(mark)  
'<__main__.User object at 0x10aef7450>'
>>> mark.__str__()  
'<__main__.User object at 0x10aef7450>'
>>> f'{mark}'  
'<__main__.User object at 0x10aef7450>'
>>> f'{mark!s}'  
'<__main__.User object at 0x10aef7450>'

16.16.2. Overloaded

Objects can verbose print if __str__() method is present:

>>> class User:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
...
...     def __str__(self):
...         return f'{self.firstname} {self.lastname}'
...
>>> mark = User('Mark', 'Watney')
>>> print(mark)
Mark Watney
>>> str(mark)
'Mark Watney'
>>> mark.__str__()
'Mark Watney'
>>> f'{mark}'
'Mark Watney'
>>> f'{mark!s}'
'Mark Watney'

16.16.3. Assignments

Code 16.24. Solution
"""
* Assignment: OOP Stringify Str
* Type: class assignment
* Complexity: easy
* Lines of code: 3 lines
* Time: 5 min

English:
    1. While printing object show: species name and a sum of `self.values`
    2. Result of sum round to one decimal place
    3. Run doctests - all must succeed

Polish:
    1. Przy wypisywaniu obiektu pokaż: nazwę gatunku i sumę `self.values`
    2. Wynik sumowania zaokrąglij do jednego miejsca po przecinku
    3. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> for row in DATA:
    ...     values = row[0:4]
    ...     species = row[4]
    ...     iris = Iris(values, species)
    ...     print(iris)
    setosa 9.4
    versicolor 16.3
    virginica 19.3
"""

DATA = [
    (4.7, 3.2, 1.3, 0.2, 'setosa'),
    (7.0, 3.2, 4.7, 1.4, 'versicolor'),
    (7.6, 3.0, 6.6, 2.1, 'virginica'),
]


class Iris:
    def __init__(self, values, species):
        self.values = values
        self.species = species