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.

146 Chapter 15. Classesand objectsBecausePointisdefined at the toplevel, its“full name” is__main__.Point.The class object is like a factory for creating objects. To create a Point, you call Point as if it wereafunction.>>> blank = Point()>>> print blankThe return value is a reference to a Point object, which we assign to blank. Creating a new objectiscalled instantiation, and the object isan instance ofthe class.When you print an instance, <strong>Python</strong> tells you what class it belongs to and where it is stored inmemory (theprefix0xmeans that the following number isinhexadecimal).15.2 AttributesYou can assignvalues toaninstance usingdot notation:>>> blank.x = 3.0>>> blank.y = 4.0This syntax is similar to the syntax for selecting a variable from a module, such as math.pi orstring.whitespace. Inthiscase,though,weareassigningvaluestonamedelementsofanobject.These elements arecalled attributes.As a noun, “AT-trib-ute” is pronounced with emphasis on the first syllable, as opposed to “a-TRIBute,”whichisaverb.The following diagram shows the result of these assignments. A state diagram that shows an objectand itsattributes iscalled anobject diagram:blankPointxy3.04.0The variableblank refers to a Point object, which contains two attributes. Each attribute refers to afloating-point number.You can read the value of an attributeusingthe samesyntax:>>> print blank.y4.0>>> x = blank.x>>> print x3.0The expression blank.x means, “Go to the object blank refers to and get the value of x.” In thiscase,weassignthatvaluetoavariablenamedx. Thereisnoconflictbetweenthevariablexandtheattributex.You can use dot notation as part of any expression. For example:

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

Saved successfully!

Ooh no, something went wrong!