Re: overloading *something



On Mon, 7 Nov 2005 20:39:46 -0800, James Stroud <jstroud@xxxxxxxxxxxx> 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
.



Relevant Pages

  • Re: overloading *something
    ... > How does one make an arbitrary class ) behave like ... > myobj = myclass() ... def totuple: ...
    (comp.lang.python)
  • Re: Module inclusion and class macro problem
    ... MyClass but in the separate Interface::xxx modules, ... limiting yourself to just one interface when you are using inheritage. ... def enforce_interface ...
    (comp.lang.ruby)
  • Re: unittest.TestCase, lambda and __getitem__
    ... > to use a single line such as def name: ... Yeah, I noticed the if thing wasn't in the PEP, but it is in the Wiki at ... self.assertRaises(IndexError, getitem, myobj, -10) ... STeve ...
    (comp.lang.python)
  • Re: adding methods at runtime
    ... myattr = "myattr" ... def method: ... instance.method = new.instancemethod(method, instance, myclass) ... The lookup mechanism will then invoke the descriptor protocol on the function object, which will return a method. ...
    (comp.lang.python)
  • Re: Dynamically generating classes?
    ... >> def initialize ... > def create_class(name, parent = nil) ... > klass = Class.new ... "MyClass" ...
    (comp.lang.ruby)