超类和子类

Super and Subclasses

我接到了一项任务,要求我们处理三个人 类:PointRectangleCanvas。我只是想知道是否有人可以帮助我大致了解他们应该如何互动。编程语言是Python 3

这是预期的输出:

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

另一个例子是:

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

如果您问自己:A 类型的对象需要定义什么?

,您将了解类型 A 的对象与其他类型之间的交互

您的 Rectangle 的一种可能实现方式是通过两个对角定义矩形,它们是平面中的点并且可以是 Point 类型。 Point 本身,可以表示为一对数字。明显的定义现在是

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

你可以定义

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

按照上面的定义,要定义Rectangle,需要两个Point对象和一个String对象。不涉及 superclass/subclass 关系。

由于您没有提供任何示例Canvas,我无法为您提供更多帮助,但我认为您可以自己完成。