12.07.2015 Views

Is Python a

Is Python a

Is Python a

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Z (instance)- datais-aSecondClass- displayis-aFirstClass- setdata- displayZ.data Z.display Z.setdataFigure 23-2. Specialization by overriding inherited names by redefining them in extensions lower inthe class tree. Here, SecondClass redefines and so customizes the “display” method for its instances.Rather than changing FirstClass, wecustomized it. Naturally, this is an artificialexample, but as a rule, because inheritance allows us to make changes like this inexternal components (i.e., in subclasses), classes often support extension and reusebetter than functions or modules can.Classes Are Attributes in ModulesBefore we move on, remember that there’s nothing magic about a class name. It’sjust a variable assigned to an object when the class statement runs, and the objectcan be referenced with any normal expression. For instance, if our FirstClass wascoded in a module file instead of being typed interactively, we could import it anduse its name normally in a class header line:from modulename import FirstClassclass SecondClass(FirstClass):def display(self): ...Or, equivalently:import modulenameclass SecondClass(modulename.FirstClass):def display(self): ...# Copy name into my scope# Use class name directly# Access the whole module# Qualify to referenceLike everything else, class names always live within a module, and so must follow allthe rules we studied in Part V. For example, more than one class can be coded in asingle module file—like other statements in a module, class statements are run duringimports to define names, and these names become distinct module attributes.More generally, each module may arbitrarily mix any number of variables, functions,and classes, and all names in a module behave the same way. The file food.pydemonstrates:# food.pyvar = 1def func( ):# food.var# food.funcClasses Are Customized by Inheritance | 471

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

Saved successfully!

Ooh no, something went wrong!