On Thu, 12 May 2005, Bernard Lebel wrote:
> Just a generic question: why one would use apply()? > > In Learning Python, on page 357, there is an example of generating an > instance using apply(): > > class A: > def __init__( self, number ): > self.number = number > > a = apply( A, 3 ) > > What is the benefit of doing this over simply creating an instance > "the usual way": > > a = A( 3 ) Hi Bernard, Just wanted to mention that Python allows us to define functions that take a variable number of arguments: ###### >>> max(1, 2, 3, 4, 5) 5 >>> def mymax(*things): ... biggest = things[0] ... for x in things: ... if x > biggest: ... biggest = x ... return biggest ... >>> mymax("this", "is", "a", "test") 'this' ###### So this 'mymax' function can take in an arbitrary number of arguments. This power comes with a slightly nonobvious problem: let's say that we had a list of things: ###### >>> words = """hello world this is a test of the emergency broadcast ... system""".split() ###### Can we call mymax() to get the maximum word in this list? We might try to brute-force this: mymax(words[0], words[1], words[2], ...) but there is a better approach: apply(mymax, words) In newer versions of Python, we have syntactic sugar to make it easier to say: "Apply this function with the elements of the input list": mymax(*words) So apply (and the * stuff) really come into play when we're doing functions with variable number of arguments. Hope this helps! _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor