[Tutor] Option of passing sequences are arguments

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 17 Jun 2001 16:58:10 -0700 (PDT)


On Sat, 16 Jun 2001, Phil Bertram wrote:

> Is it possible to unpack a sequence to fill arguments. I have been
> playing around with *args type aruments but can't seem to get it to
> work.

Yes, this is possible.


> I would like to define a class so that it can be called as follows
> 
> m = MyObject(arg1,arg2,arg3)
> 
> or
> 
> args=(arg1,arg2,arg3)
> x=MyObject(args)


It sounds like you're looking for the apply() function:

###
>>> def h(a, b):
...     return (a**2 + b**2)**.5
...
>>> args = (3, 4)
>>> apply(h, args)
5.0
###

apply() will take in a function and a tuple.  Once it has those things, it
will call h, and use the tuple as a source for the arguments.

If you want more examples, or if you have questions about it, feel free to
ask us!  Good luck!