Why the 'self' argument?

Terry Reedy tjreedy at udel.edu
Sat Sep 6 15:53:22 EDT 2003


"Isaac To" <kkto at csis.hku.hk> wrote in message
news:7ihe3pewu8.fsf at enark.csis.hku.hk...
>   class foo:
>       def __init__(msg):
>           self.msg = str(msg)
>       def f(arg):
>           print self.msg + ', ' + str(arg)
>   v = foo('hello')
>   v.f('world')     # equivalent to foo.f(v, 'world')

I think this equivalence, being an answer to the subject sentence,
needs more emphasis.  An instance method is a wrapped function and a
*class* attribute.  The 'proper' way to call such functions,
consistent with all other function calls, is klass.meth(inst,
*rest_of_args), with inst as an explicit first arg matching the
explicit first parameter in the definition.  To me, having an explicit
arg match an implicit param would be a warty inconsistency.

>From this viewpoint, inst.meth(*rest_of_args) is a conveinient
abbreviation that works because of the attribute inheritance and
lookup mechanism.  Of course, beyond being just syntactic sugar, it
adds the very important flexibility of the programmer not having to
know precisely which base class will provide the method.  I think the
long form of method call should be taught first, and then the
abbreviation and behavioral reason for its existence.  (Perhaps then,
we would have fewer threads on this topic ;-)

If an ad hoc 'self'-rule were added, the inconsistency would have to
be consistently applied to all function definitions.  Python attaches
little special importance to the presence of a def within or without a
class suite.
Absent a metaclass override that affects function wrapping only for
those in the .__new__() dict arg but not when later assigned,

class k(object): # or no object
   def f(self): pass

nicely abbreviates

def f(self): pass
class k(object): pass
k.f = f
del f

Terry J. Reedy








More information about the Python-list mailing list