tags:

views:

106

answers:

3

I know that classes can implement various special methods, such as __iter__, __setitem__, __len__, __setattr__, and many others. But when should I use them? Can anyone describe typical scenarios when I would want to implement them and they would simplify programming in Python?

Thanks, Boda Cydo.

A: 

If you're creating a class that should act sort of like an array or dictionary, these are very useful so that your syntax looks familiar. For example, if you wanted to create an ordered dictionary, you could use all of the functions you mentioned so that you could interchange that with a regular dictionary.

Dan Breen
+3  A: 

Well, the short answer is: when you need them.

Since there are a lot of built in functions I can't answer for all of them. However, you can almost all the time manage without ever overriding a builtin Python function.

Usually when you do need them is when you'd like your object to behave like a builtin datatype in Python. For example if you'd like to be able to run

len(...)

on your object (override _len_(...)), or compare two objects of your datatypes like so:

obj1 < obj2

(override _cmp_(...)) to do this.

/J

Ztyx
By the way, here is the documentation of the special Python functions if you don't have that: http://docs.python.org/reference/datamodel.html
Ztyx
specifically http://docs.python.org/reference/datamodel.html#special-method-names
Joe Koberg
+3  A: 

I think you basically answered your question.

Become familiar with the special methods. If you find that using one will make your program simpler, use it. If you don't understand what one is for, or feel like it is a more complex solution - you have answered the question. Don't use it.

The typical scenarios are :

  • Overriding operators

  • Catching access to attributes that don't exist and dealing with that access (__getattr__)

  • Manipulating class and instance creation (__init__, __slots__, __new__)

  • Customizing string representations (__str__ and __repr__)

  • allowing callability (__call__)

  • Hooking into convenient/well-used builtin syntax (__getitem__, __len__, etc...)

These are mostly covered at http://www.python.org/doc/2.5.2/ref/specialnames.html and http://docs.python.org/reference/datamodel.html#special-method-names

Joe Koberg
@Joe, you ask (maybe rhetorically?) "why implement __iter__" -- the answer is, obviously, to allow an instance of your class to be the `x` in some `for item in x: ...` loop, as is typically done with container classes. *How* you implement `__iter__` may well be with `yield`s, but it's weird to think that an answer to "how" implies anything at all about "why!_)
Alex Martelli
Indeed. I had just overlooked this usage, I guess I have only rarely needed to emulate container types....
Joe Koberg