12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

15.3. Rectangles 147>>> print '(%g, %g)' % (blank.x, blank.y)(3.0, 4.0)>>> distance = math.sqrt(blank.x**2 + blank.y**2)>>> print distance5.0You can pass an instance as an argument inthe usual way. For example:def print_point(p):print '(%g, %g)' % (p.x, p.y)print_point takes a point as an argument and displays it in mathematical notation. To invoke it,you can passblankas anargument:>>> print_point(blank)(3.0, 4.0)Insidethe function,pisan aliasforblank,soifthefunction modifiesp,blankchanges.Exercise15.1 WriteafunctioncalleddistancethattakestwoPointsasargumentsandreturnsthedistance between them.15.3 RectanglesSometimesitisobviouswhattheattributesofanobjectshouldbe,butothertimesyouhavetomakedecisions. For example, imagine you are designing a class to represent rectangles. What attributeswould you use to specify the location and size of a rectangle? You can ignore angle; to keep thingssimple, assumethat the rectangle iseither vertical or horizontal.There areat least twopossibilities:• You could specify one corner ofthe rectangle (orthecenter), thewidth, and theheight.• You could specify twoopposing corners.Atthispointitishardtosaywhethereitherisbetterthantheother,sowe’llimplementthefirstone,justas an example.Here istheclass definition:class Rectangle(object):"""represent a rectangle.attributes: width, height, corner."""The docstring lists the attributes: width and height are numbers; corner is a Point object thatspecifies thelower-left corner.Torepresentarectangle,youhavetoinstantiateaRectangleobjectandassignvaluestotheattributes:box = Rectangle()box.width = 100.0box.height = 200.0box.corner = Point()box.corner.x = 0.0box.corner.y = 0.0

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!