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 add(self, dx, dy): """Move this vector by given offset.""" self.x += dx self.y += dy 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 shift(self, dx, dy): """Move this rectangle by given offset.""" 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 as_string(self): return "([%.3f, %.3f], w=%.3f, h=%.3f)" % ( self.corner.x, self.corner.y, self.width, self.height) if __name__ == "__main__": print("create r1") r1 = Rectangle(10, 20, 30, 40) print("r1:", r1.as_string(), "area:", r1.area()) print("shift r1 by -10, -20") r1.shift(-10, -20) print("r1 shifted:", r1.as_string()) print("offset r1 by 100, 100") r2 = r1.offset(100, 100) print("r1 after offset:", r1.as_string()) print("r2 after offset:", r2.as_string())