Hi,
 
If I implement __len__ in my own class, does it really have to return an int? 
Is there no way around this (other than modifying the source code of python 
itself ;-) It would be nice if len(Example(row, col)) would return a 
dictionary, or a two-tuple (see code below). The strange thing is that calling 
__len__ directly does work: Example(1, 2).__len__() returns the dictionary. I 
always thought len() was a convenient "shorthand" for __len__. I've even been 
reading about metaclasses (interesting, dark, mysterious), thinking the answer 
might lie there. Note that my question is not whether it's a good idea to do 
this, I just find it interesting to understand how it could be done.

 
Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on 
win32
>>> class Example(object):
 def __init__(self, row, col):
  self.row = row
  self.col = col
 def __len__(self):
  return {self.row: self.col}
 >>> len(Example(1, 2))
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    len(Example(1, 2))
TypeError: an integer is required
>>> Example(1, 2).__len__()
{1: 2}


Regards,
Albert-Jan


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public 
order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to