# rect.py - a simple rectangle class # CS 313 - example for keyword arguments, string formatting, # modules, and the "__name__" variable class Rect: def __init__(self, x=0, y=0, w=0, h=0): self.x = x self.y = y self.w = w self.h = h def area(self): """ returns area of this rectangle """ return self.w * self.h def translate(self, dx, dy): """ translates this rectangle by dx, dy """ self.x += dx self.y += dy def contains(self, p): """ returns whether point p is contained in this rectangle """ px, py = p return (self.x <= px <= self.x + self.w and self.y <= py <= self.y + self.h) def __str__(self): """ returns string representation of itself """ return ("rect %3d x %3d at %3d, %3d" % (self.w, self.h, self.x, self.y)) # testing code - will only get executed if this is the "main" module, # i.e. run with "python rect.py". If this module is included by # some other file (e.g. square.py), its __name__ will be "rect" if __name__ == "__main__": a = Rect(w=5, h=7) b = Rect(x=20, y=30) c = Rect(100, 100, 30, 10) a. translate(10, 0) print "a = %s\nb = %s\nc = %s\n" % (a, b, c) print "area of c = %d" % c.area() p = (101, 101) print "a contains %s: %s" % (p, a.contains(p)) print "c contains %s: %s" % (p, c.contains(p))