12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 17Classes and methods17.1 Object-orientedfeatures<strong>Python</strong> is an object-oriented programming language, which means that it provides features thatsupport object-oriented programming.It is not easy to define object-oriented programming, but we have already seen some of its characteristics:• Programs are made up of object definitions and function definitions, and most of the computationisexpressed intermsof operations on objects.• Each object definition corresponds to some object or concept in the real world, and the functionsthat operate onthat object correspond totheways real-world objects interact.For example, the Time class defined in Chapter 16 corresponds to the way people record the timeof day, and the functions we defined correspond to the kinds of things people do with times. Similarly,the Point and Rectangle classes correspond to the mathematical concepts of a point and arectangle.So far, we have not taken advantage of the features <strong>Python</strong> provides to support object-orientedprogramming. Thesefeaturesarenotstrictlynecessary; mostofthemprovidealternativesyntaxforthingswehavealreadydone. Butinmanycases,thealternativeismoreconciseandmoreaccuratelyconveys thestructureof theprogram.For example, in the Time program, there is no obvious connection between the class definition andthe function definitions that follow. With some examination, it is apparent that every function takesat least oneTimeobject as anargument.This observation is the motivation for methods; a method is a function that is associated with aparticular class. We have seen methods for strings, lists, dictionaries and tuples. In this chapter, wewilldefine methods for user-defined types.Methods aresemantically thesame asfunctions, but there aretwosyntactic differences:• Methods are defined inside a class definition in order to make the relationship between theclass and the method explicit.

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

Saved successfully!

Ooh no, something went wrong!