[Tutor] Re: Defining a function (Joseph Q.)
Jacob S.
keridee at jayco.net
Fri Apr 15 03:08:58 CEST 2005
> Also I would like to point out that
> def foo(*args): #this allows for any number of arguments to be passed.
>
> The *args is powerful when used correctly. *args is a list of any length
> of arguments being passed to the function and/or class, and the arguments
> passed can be any type/object you want to pass .
> So you might do something like.
> def foo(*args):
> print len(args)
> # this prints the length of the list of the arguements passed
> # so using that function you would see something like. in the example I
> only used basic types but you can pass objects as well.
>>>foo(1, 2, 3, "cat", "mouse", ['bee', 'honey', 'stinger'])
> 6
> Notice that the length that is returned is only 6 but there are 8 items so
> it appears to have been passed to the function. In actuallity it is only
> 6 items. There is 3 integers, then 2 strings, then 1 list that is 3 items
> long. Thus the length of the list args is 6 items long. I wouldn't
> recomend passing mixed types like this to a function using args because it
> can get very confusing.
The star sugar sytax goes even further though....
def foo(*args):
print len(args)
foo(1,2,3,"cat","mouse",*['bee','honey','stinger'])
8
The star in the call means to apply each member of the list as an argument.
Isn't that cool?
HTH,
Jacob
More information about the Tutor
mailing list