15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

13.13. Customizing Classes with Special Methods<br />

We covered two important aspects of methods in preceding sections of this chapter: first, that methods<br />

must be bound (to an instance of their corresponding class) before they can be invoked; and second,<br />

that there are two special methods which provide the functionality of constructors and destructors,<br />

namely __init__() and __del__() respectively.<br />

In fact, __init__() and __del__() are part of a set of special methods which can be implemented. Some<br />

have the predefined default behavior of inaction while others do not and should be implemented where<br />

needed. These special methods allow for a powerful form of extending classes in <strong>Python</strong>. In particular,<br />

they allow for:<br />

● Emulating standard types<br />

● Overloading operators<br />

Special methods enable classes to emulate standard types by overloading standard operators such as +,<br />

*, and even the slicing subscript and mapping operator [ ]. As with most other special reserved<br />

identifiers, these methods begin and end with a double underscore ( __ ). Table 13.4 presents a list of<br />

all special methods and their descriptions.<br />

Table 13.4. Special Methods for Customizing Classes<br />

Special Method Description<br />

Basic Customization<br />

C.__init__(self[, arg1, ...] ) Constructor (with any optional arguments)<br />

[a] Constructor (with any optional argu ments); usually<br />

C.__new__(self[, arg1, ...] )<br />

used for setting up subclassing of immutable data types<br />

C.__del__(self) Destructor<br />

C.__str__(self) Printable string representation; str() built-in and print<br />

statement<br />

C.__repr__(self) Evaluatable string representation; repr() built-in and<br />

'' operator<br />

[b] Unicode string representation; unicode() built-in<br />

C.__unicode__(self)<br />

C.__call__(self, *args) Denote callable instances<br />

C.__nonzero__(self) Define False value for object; bool() built-in (as of 2.2)<br />

C.__len__(self) "Length" (appropriate for class); len() built-in

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

Saved successfully!

Ooh no, something went wrong!