So I’m working in Python trying to create a ShapeSet instance that contains a list of Shape instances and I need it to print out the list of Shape instances.
I can use the for loop in other parts of the code without running into an error. However, when I attempt a print statement it prints out the whole list and at the end results in error:
__str__ returned non-string (type NoneType)
I don’t understand why it fails to understand to stop at the end of the list here. (At least that’s what I think it’s doing).
Any help is greatly appreciated.
class ShapeSet:
def __init__(self):
"""
Initialize any needed variables
"""
self.collect = []
self.place = None
def __iter__(self):
"""
Return an iterator that allows you to iterate over the set of
shapes, one shape at a time
"""
self.place = 0
return self
def next(self):
if self.place >= len(self.collect):
raise StopIteration
self.place = self.place + 1
return self.collect[self.place-1]
def addShape(self, sh):
"""
Add shape sh to the set; no two shapes in the set may be
identical
sh: shape to be added
"""
s_count = 0
c_count = 0
t_count = 0
self.collect.append(sh)
for i in self.collect:
if type(sh) == Square and type(i) == Square:
if sh.side == i.side:
s_count = s_count + 1
if s_count == 2:
self.collect.remove(sh)
print('already there')
if type(sh) == Circle and type(i) == Circle:
if sh.radius == i.radius:
c_count = c_count + 1
if c_count == 2:
self.collect.remove(sh)
print('already there')
if type(sh) == Triangle and type(i) == Triangle:
if sh.base == i.base and sh.height == i.height:
t_count = t_count + 1
if t_count == 2:
self.collect.remove(sh)
print('already there')
def __str__(self):
"""
Return the string representation for a set, which consists of
the string representation of each shape, categorized by type
(circles, then squares, then triangles)
"""
for i in self.collect:
if type(i) == Square:
print ('Square with measurements ' + str(i.side))
if type(i) == Circle:
print ('Circle with measurements ' + str(i.radius))
if type(i) == Triangle:
print ('Triangle with measurements, base/height ' + str(i.base)+ ' ' + str(i.height))
Read the docstring in your
__str__function. You’re suppose to “return the string representation” notprintit. Since there is noreturnstatement in the__str__function, it returnsNone, whichprintchokes on.Instead, actually
returnthe desired string, and let the externalprintcall display it: