"Linux Gazette...making Linux just a little more fun!"

Special Method Attributes in Python

C++ programmers use 'operator overloading' to apply built-in operators to user defined classes. Thus,
a complex number class may have an addition operator which makes it possible for us to use two
objects of type 'complex' in an arithmetic expression in the same way we use integers or floating
point numbers. The Python programming language provides much of the same functionality in a simple
and elegant manner - using special method attributes. This is a quick
introduction to some of the special methods through code snippets which we wrote while trying
to digest the Python language reference. The code has been tested on Python ver 1.5.1.

The method __init__ is similar to a 'constructor' in C++. It is a
'special method' which is automatically called when an object is
being created.

We see that all member functions have a
parameter called 'self'. Now, when we call f.hello(), we are actually calling a method belonging to
class foo with the object 'f' as the first parameter. This parameter is usually called 'self'. Note
that it can be given any other name, though you are encouraged to name it that way by
convention. It is even possible to call f.hello() as foo.hello(f). C++ programmers will
find some relation between 'self' and the keyword 'this'(in C++) through which the hidden first
parameter to member function invocations can be accessed.

How objects print themselves - the __str__ special method

class foo defines a special method called __str__. We will see it in action if we run the following
test code:

f1 = foo(10,20)
print f1 # prints 'foo instance: n1=10,n2=20'

The reader is encouraged to look up the Python Language Reference and see how a similar function,
__repr__ works.

Truth value testing with __nonzero__

__nonzero__ is called to implement truth value testing. It should return 0 or 1. When this method is not defined,
__len__ is called, if it(__len__) is defined. If a class defines neither __len__ nor __nonzero__, all its
instances are considered true. This is how the language reference defines __nonzero__.

The magic of __getitem__

How would you like your object to behave like a list? The
distinguishing feature of a list (or tuple, or what is in general called a 'sequence' type)
is that it supports indexing. That is, you are able to write things like 'print a[i]'.
There is a special method called __getitem__ which has been designed to support indexing
on user defined objects. Here is an example:

There are some additional methods available like __setitem__, __delitem__, __getslice__, __setslice__,
__delslice__ .

Attribute access with __getattr__

__getattr__(self,name) is called when attribute lookup fails to find the attribute
whose name is given as the second argument. It should either raise an AttributeError exception
or return a computed attribute value.

Note that we also have a builtin function getattr(object, name). Thus, getattr(f, 'n') returns 100
and getattr(f,'m') returns the string 'no such attribute'.
It is easy to implement stuff like delegation using getattr. Here is an example:

class Boss:
def __init__(self, delegate):
self.d = delegate
def credits(self):
print 'I am the great boss, I did all that amazing stuff'
def __getattr__(self, name):
return getattr(self.d, name)
class Worker:
def work(self):
print 'Sigh, I am the worker, and I get to do all the work'
w = Worker()
b = Boss(w)
b.credits() # prints 'I am the great boss, I did all that amazing stuff'
b.work() # prints 'Sigh, I am the worker, and I get to do all the work'

Further Reading

The Python distribution comes with excellent documentation, which includes a
tutorial, language reference and library reference. If you are a beginner to
Python, you should start by reading Guido's excellent
tutorial. Then you
can browse through the
language reference
and
library reference.
This article was written with the help of the language reference.