Perhaps I am just dumb

Quinn Dunkan quinn at hork.ugcs.caltech.edu
Sat Feb 9 22:05:18 EST 2002


On 9 Feb 2002 13:37:00 -0800, wooks <wookiz at hotmail.com> wrote:
>Never got far enough into the book to look at win32. I couldn't
>understand why there were these 2 classes that were variants of a
>dictionary class and neither subclassed userdict and then the book
>says now I'm using magic methods go look up in the language reference
>(I did  - couldn't understand the raison d'etre). I think I have now
>sussed answers to both issues - the userdict class (I am guessing) is
>a recent addition and the book was at Python 1.5.2. The answer to the
>second issue (I think) is that this is how (or one of the ways)
>polymorphism is implemented. If I am indeed right on that then a

No, you're being too CS-PhD-y.  "poly-what?"  Yes, python is polymorphic, but
there's no need to get all fancy-pants about it.  I suspect that neither the 2
classes subclassed UserDict because their author didn't feel like it.  UserDict
defines a few methods for you, and can be convenient, but you don't hafta use
it.  I make dict-likes all the time, but rarely use UserDict, because it
insists I have an appropriate 'data' attribute.

The magic methods are methods that are magically called by non-method-looking
syntax.  So len(o) actually calls o.__len__() (for historical reasons, IMO),
and x[y] actually calls x.__getitem__(y) (since 'x[y]' is easier to type), and
x[y] = z calls x.__setitem__(y, z) (since it's more natural looking to people
used to infix algol-esques).

They don't have anything to do with polymorphism per se, but of course they
make it easier, as any time you define a general-purpose widely-used method
for your object (i.e. x[y] aka __getitem__ is widely-used so if you define it
your object can work with any __getitem__-using code).


If you want to hear the incomprehensible CS PhDs, go to c.l.functional and
listen to them talk about the latest extension to the haskell type system
(I still haven't been able to figure out exactly what existential
quantification or rank-2 polymorphism is, let alone 'arrows'... I get off when
the talk gets all ring/field-y).



More information about the Python-list mailing list