< BACKMake Note | BookmarkCONTINUE >
152015024128143245168232148039199167010047123209178152124239215162147039203231208138019083

Special Methods

Python exposes some special methods that are easily highlighted in the code because they start and end with __ (double underscores). These methods override (inherit) built-in functions of the same name that are provided by Python itself. The next list shows some of the most used special methods.

__init__(self)—  This is the constructor method, which is called during creation of instances. Usually, this is the place where the instance variables are initialized, among other things.

__str__(self)—  This method is called when str() is called on instances of this type. It specifies how the object must be displayed when it is used as a string (for example, when a print command is applied to an object).

__repr__(self)—  This method is called when repr() is called on instances of this type. This method provides a readable representation of the object. Usually, it is possible to re-create an object by using this method. Although not guaranteed, and the standard repr of an instance can't be executed to re-create the instance.

__getattr__(self, name)—  Implement this method to trap or modify the access to nonexisting members, for example, returning the attribute self.name.

__setattr__(self, name, value)—  This method allows you to control setting of attributes in the instance. It assigns the given value to the self.name instance's attribute. Note that you can also use "self.__dict__['attr'] = …" to set attributes from within __setattr__ (if you do it the normal way, you will get infinite recursion).

__delattr__(self,name)—  Implement this method to delete a specific attribute of an object. It's like saying del self.name.

__del__(self)—  The __del__ method covers the deletion of the object. Be careful because sometimes it isn't immediately used when an object is destroyed (JPython behavior). CPython's garbage collector destructs objects as soon as their reference count reaches zero.

__cmp__(self,other)—  Implement this method to compare and return a negative, zero, or positive number.

__hash__(self)—  Implement this method to generate a 32-bit hash index.

__nonzero__(self)—  Implement this method to return 0 or 1 for truth-value testing.

__call__(self)—  Classes that implement the __call__ method are callable, and their instances can be invoked like a function. This is the concept used by the built-in functions. The syntax obj(*args) is equivalent to obj.__call__(*args).

__getitem__(self, index)—  This method supports list indexing, returning self[index].

							
>>> class Seq:
…     def __getitem__(self, i):
…        if i < 5:
…            return i
…        else:
…            raise IndexError
…
>>> s = Seq()
>>> for i in s:
>>>    print i,
0, 1, 2, 3, 4
>>> print s[2]
2
>>> print s[6]
Traceback (innermost last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 6, in __getitem__
IndexError

						

Next, you have some more special methods that deal with sequence and number-related methods.

__len__(self)—This method is called to return the length of the instance when len() is called on an instance of this type.

__add__ (self, other)—  Implement this method to return self + other.

__sub__ (self, other)—  Implement this method to return self – other.

__mul__ (self, other)—  Implement this method to return self * other.

__div__ (self, other)—  Implement this method to return self / other.

__mod__ (self, other)—  Implement this method to return self % other.

__neg__ (self)—  Implement this method to return self negated.

__pos__ (self)—  Implement this method to return self positive.

__abs__ (self)—  This method is called to return the absolute value of self when abs() is called on instances of this type.

__inv__ (self)—  Implement this method to return the inverse of self.

__lshift__ (self, other)—  Implement this method to return self shifted left by other.

__rshift__ (self, other)—  Implement this method to return self shifted right by other.

__and__ (self, other)—  Implement this method to return the bitwise and value of self and other.

__or__ (self, other)—  Implement this method to return the bitwise or value of self and other.

__xor__ (self, other)—  Implement this method to return the bitwise exclusive or value of self and other.

__not__ (self)—  Implement this method to return the outcome of not self. (Note that there is no __not__() discipline for object instances; only the interpreter core defines this operation.)

__setitem__ (a, b, c)—  Implement this method to set the value of a at index b to c.

__delitem__ (a, b)—  Implement this method to remove the value of a at index b.

__getslice__ (a, b, c)—  Implement this method to return the slice of a from index b to index c–1.

__setslice__ (a, b, c, v)—  Implement this method to set the slice of a from index b to index c–1 to the sequence v.

__delslice__ (a, b, c)—  Implement this method to delete the slice of a from index b to index c–1.

The next example has a class definition that overrides some methods. Note that every instance of this class is callable.

					
>>> class Author:
…def __init__(self, argname):
…    self.name = argname
…def __str__(self):
…    return self.name
…def __repr__(self):
…    return `self.name`
…def __call__(self, other):
…    return self.name + other
…
>>> obj = Author("Andre")
>>> print obj
Andre
>>> obj
'Andre'
>>> obj(" Lessa")
'Andre Lessa'

				

Python 2.0 has added a special set of operators to the language, which are called augmented assignment operators. These operators can be overriden by inserting an 'i'in front of the name, for example, __isub__ implements in-place __sub__ (in other words, the -= operator).

Also in this new release, you have access to the built-in method __contains__, which gives you access to customize the in operator.

Method Attributes

A method implements some special attributes that can be accessed from within the class that implements it.

Suppose that you have a method called method:

method.__doc__—  Returns the documentation string of method.

method.__name__—  Returns the method name.

method.im_class—  Returns the class that has defined method.

method.im_self—  Returns the instance associated with method.

The next example retrieves and prints the __init__ method's documentation string.

						
>>> class c:
…     def __init__(self):
…             "This is a method "
…             print self.__init__.__doc__
…
>>> obj = c()
This is a method

					

Overloading Operators

Python operators are implemented for a class by implementing the equivalent special methods. This feature is called operator overloading.

Extensive support exists for operators overloading via the double-underscored special methods such as __add__ and __init__.

Note that the following expressions are equivalent:

						
a * b = __mul__(a, b)

len(a) = __len__(a)

a + b = __add__(a,b)

					

The following example overrides the __add__ method and returns a tuple of results.

						
>>> class c:
…     def __init__(self, x, y):
…         self.x = x
…         self.y = y
…     def __add__(self, other):
…         return (self.x + other.x, self.y + other.y)
…
>>> obj1 = c(5,2)
>>> obj2 = c(10,4)
>>> print obj1 + obj2
(15, 6)

					

Of course, in real life, you would be more likely to want to return an instance of the class c, rather than just a tuple.

Some others built-in methods you can use or overwrite are as follows:

						
__sub__(self, other)

__div__(self, other)

__abs__(self)

__hex__(self)

__int__(self)

					

Another small example

						
>>> class C:
…     def __init__(self, value):
…         self.value = value
…     def __sub__(self, other):
…         return self.value - other.value
…
>>> vara = C(5)
>>> varb = C(3)
>>> varc = vara - varb
>>> print varc
2

					


Last updated on 1/30/2002
Python Developer's Handbook, © 2002 Sams Publishing

< BACKMake Note | BookmarkCONTINUE >

Index terms contained in this section

__call__(self) method
__cmp__(self,other) method
__del__(self) method
__delattr__(self, name) method
__getattr__(self, name) method
__getitem__(self, index) method 2nd
__hash__(self) method
__init__(self) method
__len__(self) method
__nonzero__(self) method
__repr__(self) method
__setattr__(self, name, value) method
__str__(self) method
augmented assignment operators
      overriding
handling
      methods 2nd 3rd 4th 5th 6th
methods
      __call__(self)
      __cmp__(self,other)
      __del__(self)
      __delattr__(self, name)
      __getattr__(self, name)
      __getitem__(self, index) 2nd
      __hash__(self)
      __init__(self)
      __len__(self)
      __nonzero__(self)
      __repr__(self)
      __setattr__(self, name, value)
      __str__(self)
      handling 2nd 3rd 4th 5th 6th
      special 2nd 3rd
object-oriented programming (OOP)
      handling methods 2nd 3rd 4th 5th 6th
operators
     augmented assignment
            overriding
      overloading
overloading
      operators
overriding
      augmented assignment operators
programming
     object-oriented (OOP)
            handling methods 2nd 3rd 4th 5th 6th
special method 2nd 3rd

© 2002, O'Reilly & Associates, Inc.