__list__ (was: class "type" and metaclasses)

Jason Orendorff jason at jorendorff.com
Mon Jan 7 00:19:22 EST 2002


> I don't know if this question is related but it appeared to me some
> weeks ago: I can define __int__ etc. in my classes to provide an
> "opportunity" for int() to "convert" an instance of my class into an
> int. I have not seen something like this for e. g. __list__, so I could
> write something like
>
> [...sample omitted...]
>
> Is it anyhow possible?

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.

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

## Jason Orendorff    http://www.jorendorff.com/




More information about the Python-list mailing list