About ads on Siafoo
spacer License Creative Commons Attribution Non-Commercial Share Alike 3.0-US
Keywords spacer
operator overloading (1) Python (6) python tricks (2) tricks (7) underscore methods (2)
Related
spacer Python Tips, Tricks, and Hacks
spacer Python Decorators Don't Have to be (that) Scary
spacer Type Checking in Python
spacer Famous Code
spacer BogoSort
Permissions
spacer Owner: David
spacer Group Owner: iCapsid
spacer Viewable by Everyone
spacer Editable by All Siafoo Users
spacer Browse Articles Python __Underscore__ Methods
spacer
Solve a problem – Filter by language, license, keyword, owner, or search text to find code & info fast. Join Siafoo Now or Learn More

spacer Python __Underscore__ Methods spacer 1

By David
Updated 24 days ago (07 Apr 2012 at 04:55 AM) history recent activity
spacer Edit spacer Add to Library spacer Subscribe
spacer Send spacer Report
spacer spacer spacer spacer spacer spacer
Need to override an operator in your Python class? Ever wonder what all those double-underscore class methods do? Here's your answer. Note that this is a work in progress, feel free to add to it -- the list of methods & properties that I know about is at the bottom.
Languages Python
About ads on Siafoo

Contents

  • 1   Intro
  • 2   Class and Instance Methods
    • 2.1   Creation, Calling, and Destruction
    • 2.2   Conversion to Strings
    • 2.3   Truth Testing
    • 2.4   Comparisons
      • 2.4.1   "Rich Comparison" Operators
    • 2.5   Logical and Mathematical Operators
      • 2.5.1   Regular Binary Operations
      • 2.5.2   Reversed Binary Operations
      • 2.5.3   In-Place Binary Operations
      • 2.5.4   Unary Operations
    • 2.6   Casts
      • 2.6.1   Real Numbers
        • 2.6.1.1   Slice Indices
      • 2.6.2   Complex Numbers
    • 2.7   Containing Items
      • 2.7.1   Basics
      • 2.7.2   Items and Slices
        • 2.7.2.1   Items and New-Style Slices
        • 2.7.2.2   Old-Style Slices
    • 2.8   Attribute Access
    • 2.9   Being Contained By Another Object
      • 2.9.1   Descriptors
    • 2.10   Pickling
      • 2.10.1   Serializing and Unserializing Data
      • 2.10.2   Customizing Object Creation upon Unpickling
      • 2.10.3   Total Control
      • 2.10.4   One More Thing
    • 2.11   Copying
    • 2.12   "With" Statements
    • 2.13   Really Complicated
  • 3   Class Methods
  • 4   Class & Instance Properties
  • 5   Class & Function Properties
  • 6   File Properties
  • 7   Builtin Functions
  • 8   Module Properties
  • 9   Modules
  • 10   Other Things I've Seen Around
  • 11   Talk about in Intro/Conclusion?

1   Intro

My intention for this article is to be a quick-reference guide: all the information you might need about a method or property condensed into a few lines. This might not be possible for something like __slots__, perhaps we should link to the Python Docs for details on the more complex ones. I know this stuff is documented in other places (for example, docs.python.org/ref/specialnames.html), but it's all over the place and hard to mentally parse. I want to teach while at the same time to be brief, if that is possible.

Anyways feel free to add, don't worry about messing stuff up, I can always revert your edits if I really hate them ; ) A list of underscore methods that I haven't written about yet is at the bottom; there might be more too that I don't know about. And things I'm not sure about have question marks next to them, feel free to search for question marks and correct any uncertainties.

2   Class and Instance Methods

For consistency's sake, let's say we have a class called 'Class', instances called 'x' and 'y'. Keeping with the Python docstrings, '<==>' can be read as 'is equivalent to'.

2.1   Creation, Calling, and Destruction

__init__(self, ...)
Class.__init__(...) <==> x.__init__(...) <==> Class(...)
Called when class is called, or in other words when you instantiate the class. Shouldn't return any value; the created instance will be returned automatically.
If not present, nothing is called and life goes on.

__call__(self, ...)
x.__call__(...) <==> x(...)
Called when instance is called.
If not present, instance is not callable and a TypeError (object is not callable) or an AttributeError is raised. (?)

__del__(self)
Called when instance is about to be destroyed. This happens when the reference count reaches zero, probably because the instance was del'ed.
If not present, nothing is called and life goes on.

2.2   Conversion to Strings

__repr__(self)
x.__repr__() <==> repr(x) <==> `x`
Should return a string representation of the class or instance with as much information as possible, preferably something that can be passed to eval to recreate the object. Return value must be a string.
If not present, returns something like '<class __main__.Class at 0x2e6d50>' for classes and '<__main__.Class instance at 0xbfb70>' for instances.

__str__(self)
x.__str__() <==> str(x) <==> print x
Should return an informal, user-friendly string describing the class or instance. Return value must be a string.
If not present, __repr__ is tried. If that is not present, returns something like '__main__.Class' for classes and '<__main__.Class instance at 0xbfb70>' for instances.

__unicode__(self)
x.__unicode__() <==> unicode(x)
Should return an informal, user-friendly unicode string describing the class or instance. Return value must be unicode string, or a string or buffer (which will be automatically converted into a unicode string).
If not present, __str__ is called and the result is converted into a unicode string.

2.3   Truth Testing

__nonzero__(self)
bool(x) <==> x.__nonzero__()
Called by the built-in function bool, or whenever any truth-value test occurs.
Should return False, True, 0, or 1.
If not defined, __len__ is called; if both are not defined the instance always evaluates to True.

2.4   Comparisons

For instances to be meaningfully sorted, either __cmp__, __lt__, or __gt__ must be defined. If more than one is defined, __lt__ will be tried first, followed by __gt__ and then finally __cmp__.

__cmp__(self, other)
x.__cmp__(other) <==> cmp(x, other)
Should return a negative integer if instance is less than other, 0 if instance is equal to other, or a positive integer if instance is greater than other.
If not present (and other comparisons aren't present?) instances are compared by object identity ('address') (?)

2.4.1   "Rich Comparison" Operators

The following functions customarily return True or False, but can return any value. If in a boolean context, Python will call bool() on the returned value to determine truthfulness. NotImplemented should be raised if no valid comparison can be made.

If one of these methods is not defined, Python will try the opposite method with swapped arguments. For example, if you call x < other but x.__lt__ is not defined, Python will try the equivalent other.__gt__(x). If neither is not defined, x.__cmp__(other) will be tried, followed by other.__cmp__(x). If all four methods are undefined, instances are compared by object identity (address?).

Note that no other fallbacks will be performed. For example, if __le__ is not defined, Python does not call lt and eq. Similarly, Python will not fallback to __ne__ if __eq__ is not defined, or vice versa -- this can result in two instances that are 'equal' and 'not equal' at the same time.

There are no explicit 'reflected' (swapped-argument) versions of the comparison operators.

__eq__(self, other)
x.__eq__(other) <==> x == other
Must be implemented if two instances are to be perceived as identical, for example in a set.
Should return a value indicating if instance is equal to other.
If not defined or returns NotImplemented, other.__eq__(x) will be tried, followed by x.__cmp__(other) then other.__cmp__(x).

__ne__(self, other)
x.__ne__(other) <==> x != other
Should return a value indicating if instance is not equal to other.
If not defined or returns NotImplemented, other.__ne__(x) will be tried, followed by x.__cmp__(other) then other.__cmp__(x).

__lt__(self, other)
x.__lt__(other) <==> x < other
Should return a value indicating if instance is less than other.
If not defined or returns NotImplemented, other.__gt__(x) will be tried, followed by x.__cmp__(other) then other.__cmp__(x).

__le__(self, other)
x.__le__(other) <==> x <= other
Should return a value indicating if instance is less than or equal to other.
If not defined or returns NotImplemented, other.__ge__(x) will be tried, followed by x.__cmp__(other) then other.__cmp__(x).

__ge__(self, other)
x.__ge__(other) <==> x >= other
Should return a value indicating if instance is greater than or equal to other.
If not defined or returns NotImplemented, other.__le__(x) will be tried, followed by x.__cmp__(other) then other.__cmp__(x).

__gt__(self, other)
x.__gt__(other) <==> x > other
Should return a value indicating if instance is greater than other.
If not defined or returns NotImplemented, other.__lt__(x) will be tried, followed by x.__cmp__(other) then other.__cmp__(x).

2.5   Logical and Mathematical Operators

2.5.1   Regular Binary Operations

These methods implment the binary operators +, -, , /, //, %, *, <<, >>, &, |, and ^, and the functions divmod and pow.

The method may raise NotImplemented if no operation is possible with the supplied with the supplied argument(s).

If not defined or if returns NotImplemented, and the two instances belong to different classes, Python will try to call the equivalent reflected binary operator method of the other instance, with this instance as the argument.

If that method is also not defined, the relevant operation is not possible and a TypeError ('unsupported operand type') is raised.

__add__(self, other)
x.__add__(other) <==> x + other
If not defined or returns NotImplemented, other.__radd__(x) is tried.

__sub__(self, other)
x.__sub__(other) <==> x - other
If not defined or returns NotImplemented, other.__rsub__(x) is tried.

__mul__(self, other)
x.__mul__(other) <==> x * other
If not defined or returns NotImplemented`, ``other.__rmul__(x) is tried.

__div__(self, other)
x.__div__(other) <==> x / other
If from __future__ import division is used, __truediv__ is called instead.
If not defined or returns NotImplemented, other.__rdiv__(x) is tried.

__truediv__(self, other)
x.__truediv__(other) <==> x / other
Only called if from __future__ import division is used. Otherwise, __div__ is used.
If not defined or returns NotImplemented, other.__rtruediv__(x) is tried.

__floordiv__(self, other)
x.__floordiv__(other) <==> x // other
If not defined or returns NotImplemented, other.__rfloordiv__(x) is tried.

__mod__(self, other)
x.__mod__(other) <==> x % other
If not defined or returns NotImplemented, other.__rmod__(x) is tried.

__divmod__(self, other)
x.__divmod__(other) <==> divmod(x, other)
Should be equivelant to using __floordiv__ and __mod__. Should not be related to __truediv__.
If not defined or returns NotImplemented, other.__rdivmod__(x) is tried.

__pow__(self, other [, mod])
x.__pow__(other [, mod]) <==> x ** other [% mod] <==> pow(x, other [, mod])
If no mod argument is accepted, the ternary version of pow cannot be used.
If not defined or returns NotImplemented and mod argument is not given, other.__rpow__(x)
gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.