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.

As discussed previously, the _ _init_ _ constructor method seen in this code is themost commonly used operator overloading method in <strong>Python</strong>; it’s present in mostclasses. In this section, we will sample some of the other tools available in thisdomain, and look at example code that applies them in common use cases.Common Operator Overloading MethodsJust about everything you can do to built-in objects such as integers and lists has acorresponding specially named method for overloading in classes. Table 24-1 lists afew of the most common; there are many more. In fact, many overloading methodscome in multiple versions (e.g., _ _add_ _, _ _radd_ _, and _ _iadd_ _ for addition). Seeother <strong>Python</strong> books, or the <strong>Python</strong> language reference manual, for an exhaustive listof the special method names available.Table 24-1. Common operator overloading methodsMethod Overloads Called for_ _init_ _ Constructor Object creation: X= Class( )_ _del_ _ Destructor Object reclamation_ _add_ _ Operator + X +Y, X+= Y_ _or_ _ Operator | (bitwise OR) X|Y, X|= Y_ _repr_ _,_ _str_ _ Printing, conversions print X, repr(X), str(X)_ _call_ _ Function calls X()_ _getattr_ _ Qualification X.undefined_ _setattr_ _ Attribute assignment X.any = value_ _getitem_ _ Indexing X[key], for loops and other iterations if no _ _iter_ __ _setitem_ _ Index assignment X[key] = value_ _len_ _ Length len(X), truth tests_ _cmp_ _ Comparison X == Y, X < Y_ _lt_ _ Specific comparison X

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

Saved successfully!

Ooh no, something went wrong!