Special method names in python

Posted by Jeffery Yee | 5:26 PM

Just name a few frequently used special method names in python

Called to implement the built-in function len(). Should return the length of the object, an integer >= 0. Also, an object that doesn't define a __nonzero__() method and whose __len__() method returns zero is considered to be false in a Boolean context.

__getitem__(self, key)
Called to implement evaluation of self[key]. For sequence types, the accepted keys should be integers and slice objects. Note that the special interpretation of negative indexes (if the class wishes to emulate a sequence type) is up to the __getitem__() method. If key is of an inappropriate type, TypeError may be raised; if of a value outside the set of indexes for the sequence (after any special interpretation of negative values), IndexErrorshould be raised. For mapping types, if key is missing (not in the container), KeyError should be raised. Note:for loops expect that an IndexError will be raised for illegal indexes to allow proper detection of the end of the sequence.

__setitem__(self, key, value)
Called to implement assignment to self[key]. Same note as for __getitem__(). This should only be implemented for mappings if the objects support changes to the values for keys, or if new keys can be added, or for sequences if elements can be replaced. The same exceptions should be raised for improper key values as for the__getitem__() method.

__delitem__(self, key)
Called to implement deletion of self[key]. Same note as for __getitem__(). This should only be implemented for mappings if the objects support removal of keys, or for sequences if elements can be removed from the sequence. The same exceptions should be raised for improper key values as for the __getitem__() method.

This method is called when an iterator is required for a container. This method should return a new iterator object that can iterate over all the objects in the container. For mappings, it should iterate over the keys of the container, and should also be made available as the method iterkeys().Iterator objects also need to implement this method; they are required to return themselves. For more information on iterator objects, see ``Iterator Types'' in the Python Library Reference.
The membership test operators (in and not in) are normally implemented as an iteration through a sequence. However, container objects can supply the following special method with a more efficient implementation, which also does not require the object be a sequence.

__contains__(self, item)
Called to implement membership test operators. Should return true if item is in self, false otherwise. For mapping objects, this should consider the keys of the mapping rather than the values or the key-item pairs.
__getslice__(self, i, j)
Deprecated since release 2.0. Support slice objects as parameters to the __getitem__() method.

Called to implement evaluation of self[i:j]. The returned object should be of the same type as self. Note that missing i or j in the slice expression are replaced by zero or sys.maxint, respectively. If negative indexes are used in the slice, the length of the sequence is added to that index. If the instance does not implement the__len__() method, an AttributeError is raised. No guarantee is made that indexes adjusted this way are not still negative. Indexes which are greater than the length of the sequence are not modified. If no __getslice__()is found, a slice object is created instead, and passed to __getitem__() instead.

__setslice__(self, i, j, sequence)
Called to implement assignment to self[i:j]. Same notes for i and j as for __getslice__().This method is deprecated. If no __setslice__() is found, or for extended slicing of the form self[i:j:k], a slice object is created, and passed to __setitem__(), instead of __setslice__() being called.

__delslice__(self, i, j)
Called to implement deletion of self[i:j]. Same notes for i and j as for __getslice__(). This method is deprecated. If no __delslice__() is found, or for extended slicing of the form self[i:j:k], a slice object is created, and passed to __delitem__(), instead of __delslice__() being called.
Notice that these methods are only invoked when a single slice with a single colon is used, and the slice method is available. For slice operations involving extended slice notation, or in absence of the slice methods, __getitem__(),__setitem__() or __delitem__() is called with a slice object as argument.

Emulating numeric types

The following methods can be defined to emulate numeric objects. Methods corresponding to operations that are not supported by the particular kind of number implemented (e.g., bitwise operations for non-integral numbers) should be left undefined.

__add__(self, other)
__sub__(self, other)
__mul__(self, other)
__floordiv__(self, other)
__mod__(self, other)
__divmod__(self, other)
__pow__(self, other[, modulo])
__lshift__(self, other)
__rshift__(self, other)
__and__(self, other)
__xor__(self, other)
__or__(self, other)
These methods are called to implement the binary arithmetic operations (+-*//%divmod()pow()**,<<>>&^|). For instance, to evaluate the expression x+y, where x is an instance of a class that has an__add__() method, x.__add__(y) is called. The __divmod__() method should be the equivalent to using__floordiv__() and __mod__(); it should not be related to __truediv__() (described below). Note that__pow__() should be defined to accept an optional third argument if the ternary version of the built-in pow()function is to be supported.If one of those methods does not support the operation with the supplied arguments, it should returnNotImplemented.

__div__(self, other)
__truediv__(self, other)
The division operator (/) is implemented by these methods. The __truediv__() method is used when__future__.division is in effect, otherwise __div__() is used. If only one of these two methods is defined, the object will not support division in the alternate context; TypeError will be raised instead.

__radd__(self, other)
__rsub__(self, other)
__rmul__(self, other)
__rdiv__(self, other)
__rtruediv__(self, other)
__rfloordiv__(self, other)
__rmod__(self, other)
__rdivmod__(self, other)
__rpow__(self, other)
__rlshift__(self, other)
__rrshift__(self, other)
__rand__(self, other)
__rxor__(self, other)
__ror__(self, other)
These methods are called to implement the binary arithmetic operations (+-*/%divmod()pow()**<<,>>&^|) with reflected (swapped) operands. These functions are only called if the left operand does not support the corresponding operation and the operands are of different types.3.3 For instance, to evaluate the expression x-y, where y is an instance of a class that has an __rsub__() method, y.__rsub__(x) is called if x.__sub__(y)returns NotImplemented.Note that ternary pow() will not try calling __rpow__() (the coercion rules would become too complicated).
Note: If the right operand's type is a subclass of the left operand's type and that subclass provides the reflected method for the operation, this method will be called before the left operand's non-reflected method. This behavior allows subclasses to override their ancestors' operations.

__iadd__(self, other)
__isub__(self, other)
__imul__(self, other)
__idiv__(self, other)
__itruediv__(self, other)
__ifloordiv__(self, other)
__imod__(self, other)
__ipow__(self, other[, modulo])
__ilshift__(self, other)
__irshift__(self, other)
__iand__(self, other)
__ixor__(self, other)
__ior__(self, other)
These methods are called to implement the augmented arithmetic operations (+=-=*=/=//=%=**=<<=,>>=&=^=|=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self). If a specific method is not defined, the augmented operation falls back to the normal methods. For instance, to evaluate the expression x+=y, where x is an instance of a class that has an __iadd__() method, x.__iadd__(y) is called. If x is an instance of a class that does not define a__iadd__() method, x.__add__(y) and y.__radd__(x) are considered, as with the evaluation of x+y.

Called to implement the unary arithmetic operations (-+abs() and ~).

Called to implement the built-in functions complex()int()long(), and float(). Should return a value of the appropriate type.

Called to implement the built-in functions oct() and hex(). Should return a string value.

Called to implement operator.index(). Also called whenever Python needs an integer object (such as in slicing). Must return an integer (int or long). New in version 2.5.

__coerce__(self, other)
Called to implement ``mixed-mode'' numeric arithmetic. Should either return a 2-tuple containing self and otherconverted to a common numeric type, or None if conversion is impossible. When the common type would be the type of other, it is sufficient to return None, since the interpreter will also ask the other object to attempt a coercion (but sometimes, if the implementation of the other type cannot be changed, it is useful to do the conversion to the other type here). A return value of NotImplemented is equivalent to returning None.

Difference between _, __ and __xx__ in Python

When learning Python many people don't really understand why so much underlines in the beginning of the methods, sometimes even in the end like __this__! I've already had to explain it so many times, it's time to document it.

One underline in the beginning

Python doesn't have real private methods, so one underline in the beginning of a method or attribute means you shouldn't access this method, because it's not part of the API. It's very common when using properties:
class BaseForm(StrAndUnicode):
    def _get_errors(self):
        "Returns an ErrorDict for the data provided for the form"
        if self._errors is None:
        return self._errors
    errors = property(_get_errors)
This snippet was taken from django source code (django/forms/forms.py). This meanserrors is a property, and it's part of the API, but the method this property calls,_get_errors, is "private", so you shouldn't access it.

Two underlines in the beginning

This one causes a lot of confusion. It should not be used to mark a method as private, the goal here is to avoid your method to be overridden by a subclass. Let's see an example:
class A(object):
    def __method(self):
        print "I'm a method in A"
    def method(self):
a = A()
The output here is
$ python example.py 
I'm a method in A
Fine, as we expected. Now let's subclass A and customize __method
class B(A):
    def __method(self):
        print "I'm a method in B"

b = B()
and now the output is...
$ python example.py
I'm a method in A
as you can see, A.method() didn't call B.__method() as we could expect. Actually this is the correct behavior for __. So when you create a method starting with __ you're saying that you don't want anybody to override it, it will be accessible just from inside the own class.
How python does it? Simple, it just renames the method. Take a look:
a = A()
a._A__method()  # never use this!! please!
$ python example.py
I'm a method in A
If you try to access a.__method() it won't work either, as I said, __method is just accessible inside the class itself.

Two underlines in the beginning and in the end

When you see a method like __this__, the rule is simple: don't call it. Why? Because it means it's a method python calls, not you. Take a look:
>>> name = "igor"
>>> name.__len__()
>>> len(name)

>>> number = 10
>>> number.__add__(20)
>>> number + 20
There is always an operator or native function that calls these magic methods. The idea here is to give you the ability to override operators in your own classes. Sometimes it's just a hook python calls in specific situations. __init__(), for example, is called when the object is created so you can initialize it. __new__() is called to build the instance, and so on...
Here's an example:
class CrazyNumber(object):
    def __init__(self, n):
        self.n = n
    def __add__(self, other):
        return self.n - other
    def __sub__(self, other):
        return self.n + other
    def __str__(self):
        return str(self.n)

num = CrazyNumber(10)
print num           # 10
print num + 5       # 5
print num - 20      # 30
Another example:
class Room(object):

    def __init__(self):
        self.people = []

    def add(self, person):

    def __len__(self):
        return len(self.people)

room = Room()
print len(room)     # 1
The documentation covers all these special methods.


Use _one_underline to mark you methods as not part of the API. Use__two_underlines__ when you're creating objects to look like native python objects or you wan't to customize behavior in specific situations. And don't use __just_to_underlines, unless you really know what you're doing!

1. First, take backup of your blogger template

2. After that open your blogger template (In Edit HTML mode) & copy the all css given in this link before</b:skin> tag

3. Paste the followig code before </head> tag

<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shCore.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCpp.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCSharp.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCss.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushDelphi.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushJava.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushJScript.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushPhp.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushPython.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushRuby.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushSql.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushVb.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushXml.js' type='text/javascript'></script>
Of course, you don't need that many brushes, just keep what you really need. 

4. Paste the following code before </body> tag.
<script language='javascript'>
5. Save Blogger Template.

6. Now syntax highlighting is ready to use you can use it with <pre></pre> tag.
<pre name="code">
...Your html-escaped code goes here...

<pre name="code" class="php">
    echo "I like PHP";

7. You can Escape your code here.
8. Here is list of supported language for <class> attribute.

Popular Posts