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.

<strong>Is</strong> this a useful feature or a dangerous trap? You be the judge. You can actually getwork done by changing class attributes without ever making a single instance; thistechnique can simulate “records” or “structs” in other languages. As a refresher, considerthe following unusual but legal <strong>Python</strong> program:class X: passclass Y: passX.a = 1X.b = 2X.c = 3Y.a = X.a + X.b + X.c# Make a few attribute namespaces# Use class attributes as variables# No instances anywhere to be foundfor X.i in range(Y.a): print X.i # Prints 0..5Here, the classes X and Y work like “fileless” modules—namespaces for storing variableswe don’t want to clash. This is a perfectly legal <strong>Python</strong> programming trick, butit’s less appropriate when applied to classes written by others; you can’t always besure that class attributes you change aren’t critical to the class’ internal behavior. Ifyou’re out to simulate a C struct, you may be better off changing instances thanclasses, as that way, only one object is affected:class Record: passX = Record( )X.name = 'bob'X.job = 'Pizza maker'Multiple Inheritance: Order MattersThis may be obvious, but it’s worth underscoring: if you use multiple inheritance,the order in which superclasses are listed in the class statement header can be critical.<strong>Python</strong> always searches superclasses from left to right, according to their order inthe header line.For instance, in the multiple inheritance example we saw in Chapter 25, supposethat the Super class implemented a _ _repr_ _ method, too; would we want to inheritLister’s or Super’s? We would get it from whichever class is listed first in Sub’s classheader, as inheritance searches proceed from left to right. Presumably, we would listLister first because its whole purpose is its custom _ _repr_ _:class Lister:def _ _repr_ _(self): ...class Super:def _ _repr_ _(self): ...class Sub(Lister, Super):# Get Lister's _ _repr_ _ by listing it firstBut now suppose Super and Lister have their own versions of other same-namedattributes, too. If we want one name from Super, and another from Lister, the order560 | Chapter 26: Advanced Class Topics

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

Saved successfully!

Ooh no, something went wrong!