[Tutor] adding methods to native types
Erik Price
erikprice@mac.com
Thu Feb 6 00:03:07 2003
On Wednesday, February 5, 2003, at 11:43 PM, Sean 'Shaleh' Perry wrote:
> The nice thing about functions is you can pass any object to them.
> len() works
> on any object that supports __len__().
Strangely, it is more reassuring knowing that len() is just calling
__len__(). I suppose because at least then the element-counting
functionality *is* encapsulated within the class, which is where [I
think] it should be.
So does that mean that if I define a class and add a __len__() method,
then it will work with the len() function? Let me try:
>>> class TestLen:
... def __len__(self):
... return 8080
...
>>> t = TestLen()
>>> len(t)
8080
Guess so! But if the len() function simply calls the __len__() method,
why make that method "magic" at all? Why not just offer it as a
regular method? [To me] there's nothing magic about using a method to
get some data about an object.
Erik
--
Erik Price
email: erikprice@mac.com
jabber: erikprice@jabber.org