Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
"None" in array
#1
I am getting None in an array as output with the following code. Basically there are 3 items in the list which I can print as only three items. When the iterator is doing the draw from each object, output from the program in between each one is a "None" for some reason.
class Shape:
    def __init__(self):
        self.name = "Shape"
        
    def draw(self):
        raise NotImplementedError("Please Implement this method")

class Rectangle(Shape):
    def __init__(self):
        self.name = "Rectangle"
        
    def draw(self):
        print("This object is a rectangle.")

class Circle(Shape):
    def __init__(self):
        self.name = "Circle"
        
    def draw(self):
        print("This object is a circle.")

class Square(Shape):
    def __init__(self):
        self.name = "Square"
        
    def draw(self):
        print("This object is a square.")
        
if __name__ == "__main__":
    shapes = []
    inst = Rectangle()
    shapes.append(inst)
    inst = Circle()
    shapes.append(inst)
    inst = Square()
    shapes.append(inst)
    
    print(len(shapes))
    print(shapes)
    for i in shapes:
        print(i.draw())
Output:
3 [<__main__.Rectangle object at 0x7f8704639390>, <__main__.Circle object at 0x7f87046393c8>, <__main__.Square object at 0x7f8704639400>] This object is a rectangle. None This object is a circle. None This object is a square. None
Reply
#2
This is because
    for i in shapes:
        print(i.draw())
the print here is printing the result of the method draw and as there is no return value it defaults to None
remove the print and it will no longer print None.
    for i in shapes:
        i.draw()
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020