Write Pythonic Code Like a Seasoned Developer Transcripts
Chapter: Methods and Functions
Lecture: Variable argument counts for overloads
0:01 Another way to add flexibility to functions is
0:03 to allow you to pass a variable number or maybe more correctly
0:06 an arbitrary number of parameters to it.
0:10 So let's look at that in this case of the silly function I wrote called biggest,
0:13 so biggest will take two numbers,
0:16 any really two comparables and tell you which one is bigger,
0:19 so like biggest of 1 and 7, surprise, it's 7.
0:22 Let's go look at this in code.
0:24 Here we have the same thing as on our slides,
0:26 if we run this, you can see still 7 is bigger than 1, hasn't changed.
0:30 Cool, but what if we want to have more than 1 argument,
0:34 what if we wanted to somehow let's go in and write the code
0:39 what if we wanted to say the biggest of 1 and 7 and 42 and 99 and -1 and 11;
0:45 what if I wanted to write that code?
0:48 Well, if I try it's obviously not going to love it
0:51 because it says it took two positional parameters I was given 6,
0:54 not a good deal, so we can use convention here in Python called * args,
1:00 so star, args is the convention, * (star) is the keyword or the language feature,
1:06 that says this thing is going to accept an arbitrary number of parameters,
1:10 the x means first it means you have to supply at least one but you may supply more,
1:14 so let's first of all just print out what is this args and what is it
1:20 and let's comment that out for a moment,
1:22 if I try this again, you can see that I was given a tuple 7, 42 and so on,
1:27 if we look here that's the remainder after the x.
1:31 So let's go write the code that actually does the biggest part here,
1:39 there, that seems like a reasonable implementation,
1:41 we'll start out assuming the one that we have is the biggest
1:44 and we'll go through everything that was passed to us as many arguments,
1:47 zero or more that you give us and we'll check, well is this one bigger,
1:50 if it is we'll set that one to be the result.
1:52 So what should the answer be at the end- 99 of course.
1:55 Boom, and it is.
1:58 So here is another Pythonic way to add flexibility to your methods,
2:02 in a graphic, we saw we had this limited version
2:05 that could compare two things using * args
2:09 we were able to upgrade it to take an arbitrary number of items
2:12 and we saw that the thing that's passed in the args
2:15 is actually a tuple and we just loop over it
2:17 or do whatever you want to do with the tuple of additional parameters.