__list__ (was: class "type" and metaclasses)

Stefan Schwarzer s.schwarzer at ndh.net
Mon Jan 7 14:55:44 EST 2002


Hello Jason

thanks for this reply.

Jason Orendorff wrote:
> Well, yes...  If you implement __getitem__() or __iter__(),
> then list() and dict() will use those.  For example,
> 
>   import os
> 
>   class Dir:
>       def __init__(self, path):
>           self.path = path
>       def __iter__(self):
>           return iter(os.listdir(self.path))
> 
>   d = Dir("c:\\")
>   x = list(d)
>   print x
> 
> Of course, hypothetical __list__() or __dict__() methods
> would have been another possible design.  But I think the
> existing behavior is precisely what you'd normally want.

yes

> I've never used __int__() or __float__(); I use __str__()
> all the time, but mostly for debug reasons.

I think __int__ and __float__ are mostly for numeric types as the
docs suggest. I use __str__ for "nice" "human-readable" output and
__repr__ for debug output.

Stefan



More information about the Python-list mailing list