Why the 'self' argument?

Dave Brueck dave at pythonapocrypha.com
Sat Sep 6 04:36:10 EDT 2003


On Saturday 06 September 2003 02:17 pm, Terry Reedy wrote:
> The main virtue of the inst.meth(*rest) abbreviation, with klass made
> implicit, is not just to save typing the klass name but to push
> determination of which 'klass' to the runtime inheritance tree,

Pardon me if this was mentioned previously, but another benefit is to simplify 
the process of passing methods or stand-alone functions around - the user of 
such functions doesn't have to differentiate between the two:

class Foo:
  def OnEvent(self, a, b):
    print 'Method', a, b

def Listener(a, b):
  print 'Function', a,b

def SomeEventGenerator(eventListener):
  eventListener(5, 6)

SomeEventGenerator doesn't care if the callback is actually a method or a 
function. Both these work just fine:

f = Foo()
SomeEventGenerator(foo.OnEvent)
SomeEventGenerator(Listener)

Obviously, if the shorthand inst.meth(*rest) wasn't available there would 
probably be another way to do the same thing, but "inst.meth" is concise and 
does what you'd expect.

-Dave





More information about the Python-list mailing list