In addition to __init__ and
__str__ there are a number of methods which are
appropriate for classes of all kinds.
Called when a new instance of the is created. Not that this
overrides any superclass __init__ method;
to to superclass initialization first, you must evaluate the
superclass __init__ like this:
The super function identifies the superclass
of your class,
Called when the this object is no longer referenced anywhere
in the running program; the object is about to be removed by
garbage collection. This is rarely used. Note that this is called
as part of Python garbage collection; it is not called by the
self) → String
Called by the repr built-in function.
Typically, the string returned by this will look like a valid
Python expression to reconstruct the object.
self) → String
Called by the str built-in function.
This is called implicitly by the print
statement to convert an object to a convenient,
“pretty” string representation.
self, other) →
Called by all comparison operations, including the
cmp function. This must return a negative
integer if self < other,
zero if self == other, a
positive integer if self >
other. If no __cmp__
operation is defined, class instances are compared by object
In addition to the basic __cmp__,
there are additional methods which can be used to define the
behaviors of individual comparison operators. These include
__ge__ which match the operators
<, <=, ==,
!=, > and >=.
self ) → int
Called during dictionary operations, and by the built-in
function hash to transform an object to a
unique 32-bit integer hash value. Objects which compare equal
(__cmp__ returns 0) should also have the
same hash value. If a class does not define a
__cmp__ method it should not define a
__hash__ operation either. Classes with
mutable objects can define __cmp__ but
should not define __hash__, or objects
would move around in the dictionary.
self ) → boolean
Called during truth value testing; must return 0 or 1. If
this method is not defined, and __len__
is defined, then __len__ is called based
on the assumption that this is a collection. If neither function
is defined, all values are considered
Chapter 24. Creating or Extending Data Types
Special Attribute Names
Published under the terms of the Open Publication License