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.

Name mangling happens only in class statements, and only for names that beginwith two leading underscores. However, it happens for every name preceded withdouble underscores, including method names and instance attribute names (forexample, in our Spam class, the instance attribute reference self._ _X would be transformedto self._Spam_ _X). Because more than one class may add attributes to aninstance, this mangling helps avoid clashes—but we need to move on to an exampleto see how.Why Use Pseudoprivate Attributes?The problem that the pseudoprivate attribute feature is meant to alleviate has to dowith the way instance attributes are stored. In <strong>Python</strong>, all instance attributes wind upin the single instance object at the bottom of the class tree. This is very different fromthe C++ model, where each class gets its own space for data members it defines.Within a class method in <strong>Python</strong>, whenever a method assigns to a self attribute (e.g.,self.attr = value), it changes or creates an attribute in the instance (inheritancesearches only happen on reference, not on assignment). Because this is true even ifmultiple classes in a hierarchy assign to the same attribute, collisions are possible.For example, suppose that when a programmer codes a class, she assumes that sheowns the attribute name X in the instance. In this class’ methods, the name is set, andlater fetched:class C1:def meth1(self): self.X = 88def meth2(self): print self.X# Assume X is mineSuppose further that another programmer, working in isolation, makes the sameassumption in a class that she codes:class C2:def metha(self): self.X = 99def methb(self): print self.X# Me tooBoth of these classes work by themselves. The problem arises if the two classes areever mixed together in the same class tree:class C3(C1, C2): ...I = C3( ) # Only 1 X in I!Now, the value that each class gets back when it says self.X will depend on whichclass assigned it last. Because all assignments to self.X refer to the same singleinstance, there is only one X attribute—I.X—no matter how many classes use thatattribute name.To guarantee that an attribute belongs to the class that uses it, prefix the name withdouble underscores everywhere it is used in the class, as in this file, private.py:class C1:def meth1(self): self._ _X = 88def meth2(self): print self._ _X# Now X is mine# Becomes _C1_ _X in I544 | Chapter 26: Advanced Class Topics

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

Saved successfully!

Ooh no, something went wrong!