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.

148 Chapter 15. Classesand objectsTheexpressionbox.corner.xmeans,“Gototheobjectboxreferstoandselecttheattributenamedcorner;then gotothat object and select theattributenamedx.”The figure shows thestateof thisobject:Rectangleboxwidthheightcorner100.0200.0Pointxy0.00.0Anobject that isanattribute ofanother object isembedded.15.4 Instancesas returnvaluesFunctions can return instances. For example, find_center takes a Rectangle as an argument andreturns aPointthat contains thecoordinates of thecenter of theRectangle:def find_center(box):p = Point()p.x = box.corner.x + box.width/2.0p.y = box.corner.y + box.height/2.0return pHere isanexample that passesboxas an argument and assignsthe resultingPoint tocenter:>>> center = find_center(box)>>> print_point(center)(50.0, 100.0)15.5 ObjectsaremutableYoucanchangethestateofanobjectbymakinganassignmenttooneofitsattributes. Forexample,to change the size of a rectangle without changing its position, you can modify the values of widthandheight:box.width = box.width + 50box.height = box.width + 100Youcanalsowritefunctionsthatmodifyobjects. Forexample,grow_rectangletakesaRectangleobjectandtwonumbers,dwidthanddheight,andaddsthenumberstothewidthandheightoftherectangle:def grow_rectangle(rect, dwidth, dheight) :rect.width += dwidthrect.height += dheightHere isanexample that demonstrates theeffect:

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

Saved successfully!

Ooh no, something went wrong!