overloading *something
James Stroud
jstroud at mbi.ucla.edu
Mon Nov 7 23:39:46 EST 2005
On Monday 07 November 2005 20:21, Robert Kern wrote:
> James Stroud wrote:
> > Hello All,
> >
> > How does one make an arbitrary class (e.g. class myclass(object)) behave
> > like a list in method calls with the "*something" operator? What I mean
> > is:
> >
> > myobj = myclass()
> >
> > doit(*myobj)
> >
> > I've looked at getitem, getslice, and iter. What is it if not one of
> > these?
> >
> > And, how about the "**something" operator?
>
> Avoiding magic at the expense of terseness, I would do something like
> the following:
>
> class myclass(object):
> def totuple(self):
> ...
> def todict(self):
> ...
>
> myargs = myclass()
> mykwds = myclass()
>
> doit(*myargs.totuple(), **mykwds.todict())
Actually, I retried __iter__ and it worked. I'm not sure how I screwed it up
before. So I'm happy to report a little "magic":
py> def doit(*args):
... print args
...
py> class bob:
... def __init__(self, length):
... self.length = length
... def __iter__(self):
... return iter(xrange(self.length))
...
py> b = bob(8)
py> list(b)
[0, 1, 2, 3, 4, 5, 6, 7]
py> doit(*b)
(0, 1, 2, 3, 4, 5, 6, 7)
--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095
http://www.jamesstroud.com/
More information about the Python-list
mailing list