Python by Swaroop C H - HTML preview
PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.
Download the book in PDF, ePub, Kindle for a complete version.
Special Methods
There are certain special methods which have special significance in classes such as the__init__ and __del__ methods whose significance we have already seen.Generally, special methods are used to mimic certain behavior. For example, if you want to use the x[key] indexing operation for your class (just like you use for lists and tuples) then just implement the __getitem__() method and your job is done. If you think about it, this is what Python does for the list class itself!
Some useful special methods are listed in the following table. If you want to know about all the special methods, then a huge list is available in the Python Reference Manual.Table 15.1. Some Special Methods
Name__init__(self, ...)
__del__(self) __str__(self)
__lt__(self, other)
__getitem__(self, key) __len__(self)
Explanation
This method is called just before the newly created object is returned for usage.
Called just before the object is destroyed
Called when we use theprint statement with the object or whenstr() is used.
Called when the less than operator ( < ) is used. Similarly, there are special methods for all the operators (+, >, etc.)
Called whenx[key] indexing operation is used. Called when the built-inlen() function is used for the sequence object.