[Tutor] apply()

Michael P. Reilly arcege@shore.net
Wed, 24 Jan 2001 17:46:46 -0500 (EST)


> 
> I don't really understand when to use apply, when it is needed or useful. Can anyone think of a good example of when to use apply or a task that requires it. For some strange reason i can't seem to get my head around it and what it is used for.
> 

The purpose of apply is to call a function or method with a variable,
unknown number of arguments.  Most of the time in practice, within
Python, this is used in subclass methods to call a superclass's method.

class SpamMeal:
  def __init__(self, *ingredients):
    self.d = list(ingredients)
class BreakFast(SpamMeal):
  def __init__(self, howmany_eggs, *ingredients):
    apply(SpamMeal.__init__, # this is an unbound method, we have to pass self
      (self,) + ('eggs',) * howmany_eggs + ingredients
    )

The BreakFast.__init__ method gets called with some heretofore unknown
number of ingredients, specifically some number of eggs and other
ingredients.

  -Arcege

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------