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.

Multiple InheritanceIn a class statement, more than one superclass can be listed in parentheses in theheader line. When you do this, you use something called multiple inheritance—theclass and its instances inherit names from all listed superclasses.When searching for an attribute, <strong>Python</strong> searches superclasses in the class headerfrom left to right until a match is found. Technically, the search proceeds depth-firstall the way to the top of the inheritance tree, and then from left to right, as any of thesuperclasses may have superclasses of their own.In general, multiple inheritance is good for modeling objects that belong to morethan one set. For instance, a person may be an engineer, a writer, a musician, and soon, and inherit properties from all such sets.Perhaps the most common way multiple inheritance is used is to “mix in” generalpurposemethods from superclasses. Such superclasses are usually called mix-inclasses—they provide methods you add to application classes by inheritance. Forinstance, <strong>Python</strong>’s default way to print a class instance object isn’t incredibly useful:>>> class Spam:... def _ _init_ _(self): # No _ _repr_ _... self.data1 = "food"...>>> X = Spam( )>>> print X # Default: class, addressAs seen in the previous section on operator overloading, you can provide a _ _repr_ _method to implement a custom string representation of your own. But, rather thancoding a _ _repr_ _ in each and every class you wish to print, why not code it once ina general-purpose tool class and inherit it in all your classes?That’s what mix-ins are for. The following file, mytools.py, defines a mix-in classcalled Lister that overloads the _ _repr_ _ method for each class that includes Listerin its header line. It simply scans the instance’s attribute dictionary (remember, it’sexported in _ _dict_ _) to build up a string showing the names and values of allinstance attributes. Because classes are objects, Lister’s formatting logic can be usedfor instances of any subclass; it’s a generic tool. *Lister uses two special tricks to extract the instance’s class name and address. Eachinstance has a built-in _ _class_ _ attribute that references the class from which it wascreated, and each class has a _ _name_ _ attribute that references the name in theheader, so self.__class__._ _name_ _ fetches the name of an instance’s class. You get* For an alternative way to do this, see the person.py module example at the end of Chapter 24. It also scansattribute namespace dictionaries, but assumes there are no double-underscore names to be skipped.Multiple Inheritance | 529

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

Saved successfully!

Ooh no, something went wrong!