I get assertion error when i try to assert “” (empty string) into str function. Could anyone enlighten me as of why that happens. Totally clueless here. I know the str function needs to return a string but as far as i know it is returning a string when i run:
The error comes when i run:
JavaScript
x
3
1
menu = Menu()
2
assert menu.str() == ""
3
here is my code:
JavaScript
1
17
17
1
class Node:
2
3
def __init__(self):
4
self.counter = counter
5
my_list = []
6
self.my_list = my_list
7
8
9
def __str__(self):
10
for element in self.a_list:
11
if element:
12
return "n".join(f"{counter}. {element}" for counter,
13
element in enumerate(self.my_list, 1))
14
print()
15
16
17
Advertisement
Answer
As the declaration is def __str__(self):
you need to call it like
JavaScript
1
2
1
assert menu.__str__() == ""
2
Or using str
method
JavaScript
1
2
1
assert str(menu) == ""
2
Also you have a for loop, that includes another loop on the same a_list
. A good implementation is
JavaScript
1
12
12
1
# with classic for loop syntax
2
def __str__(self):
3
result = ""
4
for counter, element in enumerate(self.a_list, 1):
5
result += f"{counter}. {element}n"
6
return result
7
8
9
# with generator syntax
10
def __str__(self):
11
return "n".join(f"{c}. {elem}" for c, elem in enumerate(self.a_list, 1))
12