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 15Classes and objects15.1 User-definedtypesWe have used many of <strong>Python</strong>’s built-in types; now we are going to define a new type. As anexample, we willcreate atype calledPointthat represents apoint intwo-dimensional space.Inmathematicalnotation,pointsareoftenwritteninparentheseswithacommaseparatingthecoordinates.For example, (0,0) represents the origin, and (x,y) represents the point x units to the rightand yunits up fromthe origin.There areseveral ways we might represent points in<strong>Python</strong>:• We could storethecoordinates separately intwo variables,xandy.• We could storethecoordinates as elements inalistortuple.• We could create a new type torepresent points as objects.Creating a new type is (a little) more complicated than the other options, but it has advantages thatwillbe apparent soon.A user-defined type isalsocalled a class. A class definition looks likethis:class Point(object):"""represents a point in 2-D space"""This header indicates that the new class is a Point, which is a kind of object, which is a built-intype.The body is a docstring that explains what the class is for. You can define variables and functionsinsideaclass definition, but wewillget back tothat later.Defining aclass namedPointcreates aclass object.>>> print Point

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

Saved successfully!

Ooh no, something went wrong!