overloading *something

Bengt Richter bokr at oz.net
Tue Nov 8 03:22:00 EST 2005


On Mon, 7 Nov 2005 20:39:46 -0800, James Stroud <jstroud at mbi.ucla.edu> wrote:

>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)
>
I think you can also just define __getitem__ if that's handier. E.g.,

 >>> class MyClass(object):
 ...     def __init__(self, limit=1): self.limit=limit
 ...     def __getitem__(self, i):
 ...          if i < self.limit: return i**3
 ...          raise StopIteration
 ...
 >>> myobj = MyClass(5)
 >>> list(myobj)
 [0, 1, 8, 27, 64]
 >>> list(MyClass(10))
 [0, 1, 8, 27, 64, 125, 216, 343, 512, 729]

Regards,
Bengt Richter



More information about the Python-list mailing list