from __future__ import print_function """Classes for tracking the coordinates and computing some properties of rectangles.""" class Vector: """Represents a vector in 2-D space.""" def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return "[%.3f, %.3f]" % (self.x, self.y) def add(self, dx, dy): """Move this vector by given offset.""" self.x += dx self.y += dy def __add__(self, other): """Return sum of this vector and "other" as a new Vector.""" return Vector(self.x + other.x, self.y + other.y) class Rectangle: """Represents a rectangle in 2-D space. Attributes: width, height, corner.""" def __init__(self, x, y, width, height): self.corner = Vector(x, y) self.width = width self.height = height def __repr__(self): return "(%s, w=%.3f, h=%.3f)" % (self.corner, self.width, self.height) def shift(self, dx, dy): """Move this rectangle by given offset.""" self.corner += Vector(dx, dy) # Alternatively: # self.corner.add(dx, dy) def offset(self, dx, dy): """Return new rectangle shifted by given offset.""" r = Rectangle(self.corner.x, self.corner.y, self.width, self.height) r.shift(dx, dy) return r def area(self): """Return area of rectangle.""" return self.width * self.height def bounding_box(self): """Return 4-tuple of (lower-left x,y, upper-right x,y).""" llx = self.corner.x lly = self.corner.y urx = llx + self.width ury = lly + self.height return (llx, lly, urx, ury) if __name__ == "__main__": print("create r1") r1 = Rectangle(10, 20, 30, 40) print("r1:", r1, "area:", r1.area()) print("shift r1 by -10, -20") r1.shift(-10, -20) print("r1 shifted:", r1) print("offset r1 by 100, 100") r2 = r1.offset(100, 100) print("r1 after offset:", r1) print("r2 after offset:", r2)