Linux/Unix > Python Essential Reference, Second Edition > 3. Types and Objects > Special Methods | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238110137104029061153098000086086

### Special Methods

All the built-in datatypes consist of some data and a collection of special object methods. The names of special methods are always preceded and followed by double underscores (`_ _`). These methods are automatically triggered by the interpreter as a program executes. For example, the operation `x` `+` `y` is mapped to an internal method `x` `._ _add_ _ (``y` `)`, and an indexing operation `x` `[``k` `]` is mapped to `x` `._ _getitem_ _ (``k` `)`. The behavior of each datatype depends entirely on the set of special methods that it implements.

Although it’s not possible to alter the behavior of built-in types (or even to invoke any of their special methods directly by name, as just suggested), it’s possible to use class definitions to define new objects that behave like the built-in types. To do this, supply implementations of the special methods described in this section.

#### Object Creation, Destruction, and Representation

The methods in Table 3.7 initialize, destroy, and represent objects. The `_ _init_ _()` method initializes the attributes of an object and is called immediately after an object has been newly created. The `_ _del_ _( )` method is invoked when an object is about to be destroyed. This method is invoked only when an object is no longer in use. It’s important to note that the statement `delx` `x` only decrements an object’s reference count and doesn’t necessarily result in a call to this function.

##### Table 3.7. Special Methods for Object Creation, Destruction, and Representation

Method | Description
--- | ---
`_ _init_ _(``self` `[,``args` `])` | Called to initialize a new instance
`_ _del_ _(``self` `)` | Called to destroy an instance
`_ _repr_ _(``self` `)` | Creates a full string representation of an object
`_ _str_ _ (``self` `)` | Creates an informal string representation
`_ _cmp_ _(``self` `,``other` `)` | Compares two objects and returns negative, zero, or positive
`_ _hash_ _(``self` `)` | Computes a 32-bit hash index
`_ _nonzero_ _(``self` `)` | Returns `0` or `1` for truth-value testing

The `_ _repr_ _()` and `_ _str_ _()` methods create string representations of an object. The `_ _repr_ _()` method normally returns an expression string that can be evaluated to re-create the object. This method is invoked by the built-in `repr()` function and by the backquotes operator (```). For example:

    a = [2,3,4,5]      # Create a list
    s = repr(a)        # s = '[2, 3, 4, 5]'
                       # Note : could have also used s = `a`
    b = eval(s)        # Turns s back into a list

If a string expression cannot be created, the convention is for `_ _repr_ _()` to return a string of the form `<...``message` `...>`, as shown here:

    f = open("foo")
    a = repr(f)        # a = "<open file 'foo', mode 'r' at dc030>"

The `_ _str_ _()` method is called by the built-in `str()` function and by the `print` statement. It differs from `_ _repr_ _()` in that the string it returns can be more concise and informative to the user. If this method is undefined, the `_ _repr_ _()` method is invoked.

The `_ _cmp_ _(``self` `,``other` `)` method is used by the other comparison operators. It returns a negative number if `self` `<` `other` , zero if `self` `==` `other` , and positive if `self` `>` `other` . If this method is undefined for an object, the object will be compared by object identity. In addition, an object may define an alternative set of comparison functions for each of the relational operators. These are known as rich comparisons, and are described shortly. The `_ _nonzero_ _()` method is used for truth-value testing and should return `0` or `1`. If undefined, the `_ _len_ _()` method is invoked to determine truth. Finally, the `_ _hash_ _()` method computes an integer hash key used in dictionary operations. (The hash value can also be returned using the built-in function `hash()`.) The value returned should be identical for two objects that compare as equal. Furthermore, mutable objects should not define this method; any changes to an object will alter the hash value and make it impossible to locate an object on subsequent dictionary lookups. An object should not define a `_ _hash_ _()` method without also defining `_ _cmp_ _()`.

#### Attribute Access

The methods in Table 3.8 read, write, and delete the attributes of an object using the dot (`.`) operator and the `del` operator, respectively.

##### Table 3.8. Special Methods for Attribute Access

Method | Description
--- | ---
`_ _getattr_ _(``self` `,` `name` `)` | Returns the attribute `self` `.``name`
`_ _setattr_ _(``self` `,` `name` `,` `value` `)` | Sets the attribute `self` `.``name` `=` `value`
`_ _delattr_ _(``self` `,` `name` `)` | Deletes the attribute `self` `.``name`

For example:

    a = x.s       # Invokes _ _getattr_ _(x,"s")
    x.s = b       # Invokes _ _setattr_ _(x,"s", b)
    del x.s       # Invokes _ _delattr_ _(x,"s")

For class instances, the `_ _getattr_ _()` method is invoked only if the search for the attribute in the object’s local dictionary or corresponding class definition fails. This method should return the attribute value or raise an `AttributeError` exception on failure.

#### Sequence and Mapping Methods

The methods in Table 3.9 are used by objects that want to emulate sequence and mapping objects.

##### Table 3.9. Methods for Sequences and Mappings

Method | Description
--- | ---
`_ _len_ _(``self` `)` | Returns the length of `self`
`_ _getitem_ _(``self` `,` `key` `)` | Returns `self` `[``key` `]`
`_ _setitem_ _(``self` `,` `key` `,` `value` `)` | Sets `self` `[``key` `] =` `value`
`_ _delitem_ _(``self` `,` `key` `)` | Deletes `self` `[``key` `]`
`_ _getslice_ _(``self` `,``i` `,``j` `)` | Returns `self` `[``i` `:``j` `]`
`_ _setslice_ _(``self` `,``i` `,``j` `,``s` `)` | Sets `self` `[``i` `:``j` `] =` `s`
`_ _delslice_ _(``self` `,``i` `,``j` `)` | Deletes `self` `[``i` `:``j` `]`
`_ _contains_ _(``self` `,``obj` `)` | Returns `obj` in `self`

For example:

    a = [1,2,3,4,5,6]
    len(a)               # _ _len_ _(a)
    x = a[2]             # _ _getitem_ _(a,2)
    a[1] == 7            # _ _setitem_ _(a,1,7)
    del a[2]             # _ _delitem_ _(a,2)
    x = a[1:5]           # _ _getslice_ _(a,1,5)
    a[1:3] = [10,11,12]  # _ _setslice_ _(a,1,3,[10,11,12])
    del a[1:4]           # _ _delslice_ _(a,1,4)

The `_ _len_ _` method is called by the built-in `len()` function to return a non-negative length. This function also determines truth values unless the `_ _nonzero_ _()` method has also been defined.

For manipulating individual items, the `_ _getitem_ _()` method can return an item by key value. The key can be any Python object, but is typically an integer for sequences. The `_ _setitem_ _()` method assigns a value to an element. The `_ _delitem_ _()` method is invoked whenever the `del` operation is applied to a single element.

The slicing methods support the slicing operator `s` `[``i` `:``j` `]`. The `_ _getslice_ _()` method returns a slice, which is normally the same type of sequence as the original object. The indices `i` and `j` must be integers, but their interpretation is up to the method. Missing values for `i` and `j` are replaced with `0` and `sys.maxint`, respectively. The `_ _setslice_ _()` method assigns values to a slice. Similarly, `_ _delslice_ _()` deletes all the elements in a slice.

The `_ _contains_ _()` method is used to implement the `in` operator.

In addition to implementing the methods just described, sequences and mappings implement a number of mathematical methods, including `_ _add_ _()`, `_ _radd_ _()`, `_ _mul_ _()`, and `_ _rmul_ _()` to support concatenation and sequence replication. These methods are described shortly.

Finally, Python supports an extended slicing operation that’s useful for working with multidimensional data structures such as matrices and arrays. Syntactically, you specify an extended slice as follows:

    a = m[0:100:10]          # Strided slice (stride=10)
    b = m[1:10, 3:20]        # Multidimensional slice
    c = m[0:100:10, 50:75:5] # Multiple dimensions with strides
    m[0:5, 5:10] = n         # extended slice assignment
    del m[:10, 15:]          # extended slice deletion

The general format for each dimension of an extended slice is `i` `:``j` `[:``stride` `]`, where `stride` is optional. As with ordinary slices, you can omit the starting or ending values for each part of a slice. In addition, a special object known as the Ellipsis and written as `…` is available to denote any number of trailing or leading dimensions in an extended slice:

    a = m[..., 10:20]    # extended slice access with Ellipsis
    m[10:20, ...] = n

When using extended slices, the `_ _getitem_ _()`, `_ _setitem_ _()`, and `_ _delitem_ _()` methods implement access, modification, and deletion, respectively. However, instead of an integer, the value passed to these methods is a tuple containing one or more slice objects and at most one instance of the `Ellipsis` type. For example,

    a = m[0:10, 0:100:5, ...]

invokes `_ _getitem_ _()` as follows:

    a = _ _getitem_ _(m, (slice(0,10,None), slice(0,100,5), Ellipsis))

At this time, none of the built-in datatypes supports extended slices, so using them is likely to result in an error. However, special-purpose extensions, especially those with a scientific flavor, may provide new types and objects that support the extended slicing operation.

#### Mathematical Operations

Table 3.10 lists special methods that objects must implement to emulate numbers. Mathematical operations associate from left to right; when an expression such as `x` `+` `y` appears, the interpreter tries to invoke the method `x` `._ _add_ _(``y` `)`. The special methods beginning with `r` support operations with reversed operands. These are invoked only if the left operand doesn’t implement the specified operation. For example, if `x` in `x` `+` `y` doesn’t support the `_ _add_ _()` method, the interpreter tries to invoke the method `y` `._ _radd_ _(``x` `)`.

##### Table 3.10. Methods for Mathematical Operations

Method | Result
--- | ---
`_ _add_ _(``self` `,``other` `)` | `self` `+` `other`
`_ _sub_ _(``self` `,``other` `)` | `self` `-` `other`
`_ _mul_ _(``self` `,``other` `)` | `self` `*` `other`
`_ _div_ _(``self` `,``other` `)` | `self` `/` `other`
`_ _mod_ _(``self` `,``other` `)` | `self` `%` `other`
`_ _divmod_ _(``self` `,``other` `)` | `divmod(``self` `,``other` `)`
`_ _pow_ _(``self` `,``other` `[,``modulo` `])` | `self` `**` `other` `, pow(``self` `,` `other` `,` `modulo` `)`
`_ _lshift_ _(``self` `,``other` `)` | `self` `<<` `other`
`_ _rshift_ _(``self` `,``other` `)` | `self` `>>` `other`
`_ _and_ _(``self` `,``other` `)` | `self` `&` `other`
`_ _or_ _(``self` `,``other` `)` | `self` `|` `other`
`_ _xor_ _(``self` `,``other` `)` | `self` `^` `other`
`_ _radd_ _(``self` `,``other` `)` | `other` `+` `self`
`_ _rsub_ _(``self` `,``other` `)` | `other` `-` `self`
`_ _rmul_ _(``self` `,``other` `)` | `other` `*` `self`
`_ _rdiv_ _(``self` `,``other` `)` | `other` `/` `self`
`_ _rmod_ _(``self` `,``other` `)` | `other` `%` `self`
`_ _rdivmod_ _(``self` `,``other` `)` | `divmod(``other` `,``self` `)`
`_ _rpow_ _(``self` `,``other` `)` | `other` `**` `self`
`_ _rlshift_ _(``self` `,``other` `)` | `other` `<<` `self`
`_ _rrshift_ _(``self` `,``other` `)` | `other` `>>` `self`
`_ _rand_ _(``self` `,``other` `)` | `other` `&` `self`
`_ _ror_ _(``self` `,``other` `)` | `other` `|` `self`
`_ _rxor_ _(``self` `,``other` `)` | `other` `^` `self`
`_ _iadd_ _(``self` `,``other` `)` | `self` `+=` `other`
`_ _isub_ _(``self` `,``other` `)` | `self` `-=` `other`
`_ _imul_ _(``self` `,``other` `)` | `self` `*=` `other`
`_ _idiv_ _(``self` `,``other` `)` | `self` `/=` `other`
`_ _imod_ _(``self` `,``other` `)` | `self` `%=` `other`
`_ _ipow_ _(``self` `,``other` `)` | `self` `**=` `other`
`_ _iand_ _(``self` `,``other` `)` | `self` `&=` `other`
`_ _ior_ _(``self` `,``other` `)` | `self` `|=` `other`
`_ _ixor_ _(``self` `,``other` `)` | `self` `^=` `other`
`_ _ilshift_ _(``self` `,``other` `)` | `self` `<<=` `other`
`_ _irshift_ _(``self` `,``other` `)` | `self` `>>=` `other`
`_ _neg_ _(``self` `)` | `-``self`
`_ _pos_ _(``self` `)` | `+``self`
`_ _abs_ _(``self` `)` | `abs(``self` `)`
`_ _invert_ _(``self` `)` | `~``self`
`_ _int_ _(``self` `)` | `int(``self` `)`
`_ _long_ _(``self` `)` | `long(``self` `)`
`_ _float_ _(``self` `)` | `float(``self` `)`
`_ _complex_ _(``self` `)` | `complex(``self` `)`
`_ _oct_ _(``self` `)` | `oct(``self` `)`
`_ _hex_ _(``self` `)` | `hex(``self` `)`
`_ _coerce_ _(``self` `,``other` `)` | `Type coercion`

The methods `_ _iadd_ _()`, `_ _isub_ _()`, and so forth are used to support in-place arithmetic operators such as `a+=b` and `a-=b` (also known as augmented assignment). A distinction is made between these operators and the standard arithmetic methods because the implementation of the in-place operators might be able to provide certain customizations such as performance optimizations. For instance, if the `self` parameter is not shared, it might be possible to modify its value in place without having to allocate a newly created object for the result.

The conversion methods `_ _int_ _()`, `_ _long_ _()`, `_ _float_ _()`, and `_ _complex_ _()` convert an object into one of the four built-in numerical types. The `_ _oct_ _()` and `_ _hex_ _()` methods return strings representing the octal and hexadecimal values of an object, respectively.

The `_ _coerce_ _(``x` `,``y` `)` method is used in conjunction with mixed-mode numerical arithmetic. This method returns either a 2-tuple containing the values of `x` and `y` converted to a common numerical type, or `None` if no such conversion is possible. To evaluate an operation `x op y` where `op` is an operation such as `+`, the following rules are applied, in order:

1. If `x` has a `_ _coerce_ _()` method, replace `x` and `y` with the values returned by `x` `._ _coerce_ _(``y` `)`. If `None` is returned, skip to step 3.

2. If `x` has a method `_ _``op` `_ _()`, return `x` `._ _``op` `_ _(``y` `)`. Otherwise, restore `x` and `y` to their original values and continue.

3. If `y` has a `_ _coerce_ _()` method, replace `x` and `y` with the values returned by `y` `._ _coerce_ _(``x` `)`. If `None` is returned, raise an exception.

4. If `y` has a method `_ _rop_ _()`, return `y` `._ _rop_ _(``x` `)`. Otherwise, raise an exception.

Although strings define a few arithmetic operations, the `_ _coerce_ _()` method is not used in operations involving standard and Unicode strings.

The interpreter supports only a limited number of mixed-type operations involving the built-in types, in particular the following:

- If `x` is a string, `x` `%` `y` invokes the string-formatting operation, regardless of the type of `y`.

- If `x` is a sequence, `x` `+` `y` invokes sequence concatenation.

- If either `x` or `y` is a sequence and the other operand is an integer, `x` `*` `y` invokes sequence repetition.

#### Comparison Operations

Table 3.11 lists special methods that objects can implement to provide individualized versions of the relational operators (`<`, `>`, `<=`, `>=`, `==`, `!=`). These are known as rich comparisons and were first introduced in Python 2.1. Each of these functions takes two arguments and can return any kind of object, including a Boolean value, a list, or any other Python type. For instance, a numerical package might use this to perform an element-wise comparison of two matrices, returning a matrix with the results. If a comparison cannot be made, these functions may also raise an exception.

##### Table 3.11. Methods for Comparisons

Method | Result
--- | ---
`_ _lt_ _(``self` `,``other` `)` | `self` `<` `other`
`_ _le_ _(``self` `,``other` `)` | `self` `<=` `other`
`_ _gt_ _(``self` `,``other` `)` | `self` `>` `other`
`_ _ge_ _(``self` `,``other` `)` | `self` `>=` `other`
`_ _eq_ _(``self` `,``other` `)` | `self` `==` `other`
`_ _ne_ _(``self` `,``other` `)` | `self` `!=` `other`

#### Callable Objects

Finally, an object can emulate a function by providing the `_ _call_ _(``self` `[,``args` `])` method. If an object `x` provides this method, it can be invoked like a function. That is, `x` `(``arg1` `,` `arg2` `, ...)` invokes `x` `._ _call_ _(``self` `,` `arg1` `,` `arg2` `, ...)`.

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.