Search code examples
pythonsubclasssuperclass

Super and Subclasses


I have been given an assignment that asks us to deal with three individual classes: Point, Rectangle and Canvas. I was just wondering if anyone could help me get a general understanding as how they are suppose to interact. The programming language is Python 3

Here are the outputs expected:

>>>r1=Rectangle(Point(), Point(1,1), "red")
>>>r1
Rectangle(Point(0,0),Point(1,1),'red')

another example would be:

>>> r3=Rectangle(Point(), Point(2,1), "red")
>>> r3.get_perimeter()
6

Solution

  • You will get the interactions between objects of type A and the other types, if you ask yourself: What does object of type A need to be defined?

    One of the possible implementations of your Rectangle is to define rectangle via two opposite corners, which are points in the plane and can be of type Point. Point itself, could be represented as pair of numbers. The obvious definitions are now

    class Point():
        def __init__(self, x, y):
            self.xCoordinate = x
            self.yCoordinate = y
    
    
    
    class Rectangle():
        def __init__(self, southwest, northeast, colour):
            self.bottomLeftCorner = southwest
            self.upperRightCorner = northeast
            self.fill = colour
    

    and you can define

    rect = Rectangle(Point(0,1), Point(4,212), "red")
    

    Following the upper definition, to define Rectangle, one needs two Point objects and one String. No superclass/subclass relation is involved.

    Since you did not provide any examples of Canvas, I cannot help you more, but I think that you can do it on your own.