"self" - a python wart or "feature"

Alex Martelli aleaxit at yahoo.com
Mon Feb 17 06:44:45 EST 2003


Cere Davis wrote:

> Thanks but I'm having diffuculty understanding how this FAQ answers my
> question about requiring self as the first argument in a function.
> I can appreciate clarity of scope for variables but it seems to me that
> requiring an extra argument in a function that is allready indented into
> the class
> to be unnecessary.  From what little I know about Ruby, it does not
> require this for function declarations within a class.

What is or isn't "indented into a class" is basically irrelevant:


class aclass:
    def onething(): print "note: no 'self'!"
    onething = staticmethod(onething)

def another(self):
    print "note: no 'indenting into' whatever"

aclass.another = another


By coding the first argument of "self" explicitly, whenever your
function is to be used as a method in a class, and only then, you
avoid any "black magic" such as arguments appearing or not as a
compiler tries to guess your intentions.

I'm MUCH happier with a simple, no-black-magic, no-guessing rule:
"a function has a first argument, named 'self', when and only when
the function is going to be used as a method in a class".  This
may mean the function is coded within the class body (a common
case), but it need not, and it's definitely not the case that all
functions so coded are going to be used as methods (they could be
used as staticmethods instead, as for example 'onething' above).

Simple is good.  If you want compilers that try to read your mind
(and often fail), rather than ones that enforce clear, simple rules,
you know where to find complicated languages such as, e.g., PL/I.


Alex





More information about the Python-list mailing list