12.07.2015 Views

Is Python a

Is Python a

Is Python a

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

In practice, _ _str_ _ (or its low-level relative, _ _repr_ _) seems to be the second mostcommonly used operator overloading method in <strong>Python</strong> scripts, behind _ _init_ _;any time you can print an object and see a custom display, one of these two tools isprobably in use._ _radd_ _ Handles Right-Side AdditionTechnically, the _ _add_ _ method that appeared in the prior example does not supportthe use of instance objects on the right side of the + operator. To implementsuch expressions, and hence support commutative-style operators, code the _ _radd_ _method as well. <strong>Python</strong> calls _ _radd_ _ only when the object on the right side of the+ is your class instance, but the object on the left is not an instance of your class.The _ _add_ _ method for the object on the left is called instead in all other cases:>>> class Commuter:... def _ _init_ _(self, val):... self.val = val... def _ _add_ _(self, other):... print 'add', self.val, other... def _ _radd_ _(self, other):... print 'radd', self.val, other...>>> x = Commuter(88)>>> y = Commuter(99)>>> x + 1 # _ _add_ _: instance + noninstanceadd 88 1>>> 1 + y # _ _radd_ _: noninstance + instanceradd 99 1>>> x + y # _ _add_ _: instance + instanceadd 88 Notice how the order is reversed in _ _radd_ _: self is really on the right of the +, andother is on the left. Every binary operator has a similar right-side overloading method(e.g., _ _mul_ _ and _ _rmul_ _). Typically, a right-side method like _ _radd_ _ just convertsif needed, and reruns a + to trigger _ _add_ _, where the main logic is coded. Also,note that x and y are instances of the same class here; when instances of differentclasses appear mixed in an expression, <strong>Python</strong> prefers the class of the one on the left.Right-side methods are an advanced topic, and tend to be fairly rarely used in practice;you only code them when you need operators to be commutative, and then onlyif you need to support operators at all. For instance, a Vector class may use thesetools, but an Employee or Button class probably would not._ _call_ _ Intercepts CallsThe _ _call_ _ method is called when your instance is called. No, this isn’t a circulardefinition—if defined, <strong>Python</strong> runs a _ _call_ _ method for function call expressionsapplied to your instances. This allows class instances to emulate the look and feel ofthings like functions:502 | Chapter 24: Class Coding Details

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

Saved successfully!

Ooh no, something went wrong!