7.2. Operator String Str

  • Calling print(obj) calls str(obj)

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

  • Method obj.__str__() must return str

  • Intended for end-users of your class

7.2.1. Inherited

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 0x...>
>>>
>>> str(mark)  
'<__main__.User object at 0x...>'
>>>
>>> mark.__str__()  
'<__main__.User object at 0x...>'

7.2.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'Hello {self.firstname} {self.lastname}'
>>>
>>>
>>> mark = User('Mark', 'Watney')
>>>
>>> print(mark)
Hello Mark Watney
>>>
>>> str(mark)
'Hello Mark Watney'
>>>
>>> mark.__str__()
'Hello Mark Watney'

7.2.3. Assignments

Code 7.21. Solution
"""
* Assignment: Operator String Str
* Type: class assignment
* Complexity: easy
* Lines of code: 3 lines
* Time: 3 min

English:
    1. Overload `str()`
    2. While printing object show: species name and a sum of `self.features`,
       example: `label='setosa', total=9.4`
    3. Result of sum round to one decimal place
    4. Run doctests - all must succeed

Polish:
    1. Przeciąż `str()`
    2. Przy wypisywaniu obiektu pokaż: nazwę gatunku i sumę `self.features`,
       przykład: `label='setosa', total=9.4`
    3. Wynik sumowania zaokrąglij do jednego miejsca po przecinku
    4. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * f'{var=:.1f}'

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

    >>> for *features, label in DATA:
    ...     iris = Iris(features, label)
    ...     print(iris)
    label='setosa', total=9.4
    label='versicolor', total=16.3
    label='virginica', total=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:
    features: list
    label: str

    def __init__(self, features, label):
        self.features = features
        self.label = label