12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

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

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

X- dataY- datais-ais-aFirstClass- setdata- displayFigure 23-1. Classes and instances are linked namespace objects in a class tree that is searched byinheritance. Here, the “data” attribute is found in instances, but “setdata” and “display” are in theclass above them.Neither x nor y has a setdata attribute of its own, so to find it, <strong>Python</strong> follows thelink from instance to class. And that’s about all there is to inheritance in <strong>Python</strong>: ithappens at attribute qualification time, and it just involves looking up names inlinked objects (e.g., by following the is-a links in Figure 23-1).In the setdata function inside FirstClass, the value passed in is assigned to self.data.Within a method, self—the name given to the leftmost argument by convention—automatically refers to the instance being processed (x or y), so the assignments storevalues in the instances’ namespaces, not the class’ (that’s how the data names inFigure 23-1 are created).Because classes generate multiple instances, methods must go through the self argumentto get to the instance to be processed. When we call the class’ display methodto print self.data, we see that it’s different in each instance; on the other hand, thename display itself is the same in x and y, as it comes (is inherited) from the class:>>> x.display( ) # self.data differs in each instanceKing Arthur>>> y.display( )3.14159Notice that we stored different object types in the data member in each instance (astring, and a floating point). As with everything else in <strong>Python</strong>, there are no declarationsfor instance attributes (sometimes called members); they spring into existencethe first time they are assigned values, just like simple variables. In fact, if we were tocall display on one of our instances before calling setdata, we would trigger anundefined name error—the attribute named data doesn’t even exist in memory untilit is assigned within the setdata method.As another way to appreciate how dynamic this model is, consider that we canchange instance attributes in the class itself, by assigning to self in methods, or outsidethe class, by assigning to an explicit instance object:>>> x.data = "New value" # Can get/set attributes>>> x.display( ) # Outside the class tooNew value468 | Chapter 23: Class Coding Basics

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

Saved successfully!

Ooh no, something went wrong!