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.

class C2:def metha(self): self._ _X = 99def methb(self): print self._ _Xclass C3(C1, C2): passI = C3( )# Me too# Becomes _C2_ _X in I# Two X names in II.meth1( ); I.metha( )print I._ _dict_ _I.meth2( ); I.methb( )When thus prefixed, the X attributes will be expanded to include the names of theirclasses before being added to the instance. If you run a dir call on I, or inspect itsnamespace dictionary after the attributes have been assigned, you’ll see the expandednames, _C1_ _X and _C2_ _X, but not X. Because the expansion makes the namesunique within the instance, the class coders can safely assume that they truly ownany names that they prefix with two underscores:% python private.py{'_C2_ _X': 99, '_C1_ _X': 88}8899This trick can avoid potential name collisions in the instance, but note that it doesnot amount to true privacy. If you know the name of the enclosing class, you can stillaccess either of these attributes anywhere you have a reference to the instance byusing the fully expanded name (e.g., I._C1_ _X= 77). On the other hand, this featuremakes it less likely that you will accidentally step on a class’ names.Again, I should note that this feature tends to be more useful for larger, multiprogrammerprojects, and then only for selected names. Don’t be tempted to clutteryour code unnecessarily; only use this feature for names that truly need to be controlledby a single class. For simpler programs, it’s probably overkill.New-Style ClassesAlso, see the emulation of private instance attributes sketched inChapter 24, in the _ _getattr_ _ section. Although it’s possible to emulateaccess controls in <strong>Python</strong> classes, this is rarely done in practice,even for large systems.In Release 2.2, <strong>Python</strong> introduced a new flavor of classes, known as “new-style”classes; the classes covered so far in this part of the book are known as “classicclasses” when comparing them to the new kind.New-style classes are only slightly different from classic classes, and the ways inwhich they differ are completely irrelevant to the vast majority of <strong>Python</strong> users.Moreover, the classic class model, which has been with <strong>Python</strong> for some 15 years,still works exactly as I’ve described previously.New-Style Classes | 545

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

Saved successfully!

Ooh no, something went wrong!