11.2. Operator String Str

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

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

  • Method obj.__str__() must return str

  • This is dedicated for end-user of your class

11.2.1. Inherited

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

>>> class Astronaut:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
>>>
>>>
>>> astro = Astronaut('Mark', 'Watney')
>>>
>>> print(astro)  
<__main__.Astronaut object at 0x...>
>>>
>>> str(astro)  
'<__main__.Astronaut object at 0x...>'
>>>
>>> astro.__str__()  
'<__main__.Astronaut object at 0x...>'

11.2.2. Overloaded

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

>>> class Astronaut:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
...
...     def __str__(self):
...         return f'Hello {self.firstname} {self.lastname}'
>>>
>>>
>>> astro = Astronaut('Mark', 'Watney')
>>>
>>> print(astro)
Hello Mark Watney
>>>
>>> str(astro)
'Hello Mark Watney'
>>>
>>> astro.__str__()
'Hello Mark Watney'

11.2.3. Assignments

Code 11.24. Solution
"""
* Assignment: Operator String Str
* Required: yes
* Complexity: easy
* Lines of code: 3 lines
* Time: 5 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