[Tutor] special methodsy

Michael P. Reilly arcege@speakeasy.net
Tue, 8 May 2001 21:37:06 -0400 (EDT)


Katharine Stoner wrote
> In plain English, what are special methods?
> 
> -Cameron

Methods that are not called directly, but by other means.  Many are called
by operators in the language, but there are others as well.  They are all
surrounded by double underscores.  The most used is probably "__init__".

>>> class A:
...   def __init__(self, num):  # called by the instance constructor
...     self.num = num
...   def __repr__(self):       # called by `inst` and repr(s)
...     return `self.num`
...   def __str__(self):        # called by str() and print s
...     return str(self.num)
...   def __sub__(self, other): # called by A(n) - 3
...     return A(self.num - other)
...   def __rsub__(self, other): # called by 3 - A(n) [being deprecated]
...     return A(other - self.num)
...   def __cmp__(self, other):
...     return cmp(self.num, other)
...

The last one is called by all the comparison operators (==, !=, <>, <,
<=, >, >=).  In Python 2.1, they now have new special methods for each
of these.

  -Arcege

References:
Python Language Reference, 3.3 Special method names
  <URL: http://www.python.org/doc/current/ref/specialnames.html>

-- 
+----------------------------------+-----------------------------------+
| Michael P. Reilly                | arcege@speakeasy.net              |