There are several special methods that are essential to the implementation of a class. Each of them has a name that begins and ends with double underscores. These method names are used implicitly by Python. Section 3.3 of the Python Language Reference provides the complete list of these special method names.
We'll look at the special method names in depth in Chapter 24, Creating or Extending Data Types . Until then, we'll look at a few special method names that are used heavily.
The __init__
method of a class is called by Python to initialize a newly-created object
The __str__
method of a class is called whenever Python prints an object. This is the method used by the str
built-in function.
The __repr__
method of a class is used when we want to see the details of an object's values. This method is used by the repr
function.
When we sort a list of objects, the cmp
function uses the __cmp__
method of each object.
Initializing an Object with __init__
. When you create an object, Python will both create the object and also call the object's __init__
method. This function can create the object's instance variables and perform any other one-time initialization. There are, typically, two kinds of instance variables that are created by the __init__ method: variables based on parameters and variables that are independent of any parameters.
Here's an example of a company description that might be suitable for evaluating stock performance. In this example, all of the instance variables (self.name
, self.symbol
, self.price
) are based on parameters to the __init__
method.
class Company( object ): def __init__( self, name, symbol, stockPrice ): self.name= name self.symbol= symbol self.price= stockPrice def valueOf( self, shares ): return shares * self.price
When we create an instance of Company, we use code like this.
c1= Company( "General Electric", "GE", 30.125 )
This will provide three values to the parameters of __init__.
String value of an object with __str__
. The __str__
method function is called whenever an instance of a class needs to be converted to a string. Typically, this occus when we use the str
function on an object. Impicitly, when we reference object in a print statement, the str
function is evaluated. The other example is wConsider this definition of the class Card
.
class Card( object ): def __init__( self, rank, suit ): self.rank= rank self.suit= suit self.points= rank def hard( self ): return self.points def soft( self ): return self.points
When we try to print an instance of the class, we get something like the following.
>>>
c= Card( 3, "D" )
>>>
print c
<__main__.Card object at 0x2e5f6c>
This is the default behavior for the __str__
method. We can, however, override this with a function that produces a more useful-looking result.
def __str__( self ): return "%2d%s" % (self.rank, self.suit)
Adding this method function converts the current value of the die to a string and returns this. Now we get something much more useful.
>>>
d= Card( 4, "D" )
>>>
print d
4D
Representation details with __repr__
. While the __str__
method produces a human-readable string, we sometimes want the nitty-gritty details. The__repr__
method function is evaluated whenever an instance of a class must have its detailed representation shown. This is usually done in response to evaluating the repr
function. Examples include the following:
>>>
print repr(c)
<__main__.Card object at 0x2f639c>
If we would like to produce a more useful result, we can override the __repr__
function. The objective is to produce a piece of Python programming that would reconstruct the original object.
def __repr__( self ): return "Card(%d,%r)" % (self.rank,self.suit)
We use __repr__
to produce a clear definition of how to recreate the given object.
>>>
f= Card(5,"D")
>>>
print repr(f)
Card(5,'D')
Sorting and Comparing with __cmp__
. One other useful special method is __cmp__
. We use the
to provide the results used to sort and compare objects. The built-in __cmp__
cmp
function, generally, uses this method. If you don't make other arrangements, then this method is also used for <
, <=
,>
, >=
, ==
and !=
.
def __cmp__( self, other ): return cmp(self.rank, other.rank) or cmp(self.suit, self.suit)
Once we've added the __cmp__
method we can compare cards to check their relative rank.
>>>
cmp(c,d)
-1
>>>
c < d
True
>>>
c >= d
False
Special Attribute Names. In addition to the special method names, each object has a number of special attributes. These are documented in section 2.3.10 of the Python Library Reference. There are __dict__
, __class__
and __bases__
.
The attribute variables of a class instance are kept in a special dictionary object named __dict__
. As a consequence, when you say self.attribute= value
, this has almost identical meaning to self.__dict__['attribute']= value
.
Combined with the % string formatting operation, this feature is handy for writing __str__
and __repr__
functions.
def __str__( self ): return "%(rank)2s%(suit)s" % self.__dict__ def __repr__( self ): return "Card(%(rank)r,%(suit)r)" % self.__dict__