12.16. OOP Stringify Str¶
Calling function
print(obj)
callsstr(obj)
Calling function
str(obj)
callsobj.__str__()
Method
obj.__str__()
must returnstr
This is dedicated for end-user of your class
12.16.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...>'
12.16.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'
12.16.3. Assignments¶
"""
* Assignment: OOP Stringify Str
* Required: yes
* Complexity: easy
* Lines of code: 3 lines
* Time: 5 min
English:
1. While printing object show: species name and a sum of `self.features`
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.features`
2. Wynik sumowania zaokrąglij do jednego miejsca po przecinku
3. Uruchom doctesty - wszystkie muszą się powieść
Tests:
>>> import sys; sys.tracebacklimit = 0
>>> for *features, label in DATA:
... iris = Iris(features, label)
... 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, features, label):
self.features = features
self.label = label