Why I need the parameter when the call doesn't use it?

Chris Rebert clp2 at rebertia.com
Sun Aug 28 21:52:03 EDT 2011


On Sun, Aug 28, 2011 at 5:26 PM, Niklas Rosencrantz <niklasro at gmail.com> wrote:
> I modularize code for a webapp and I want to know what python makes that a need to define an argument called self? Here's some code where I'm modularizing a recaptcha test to a function and the I must add the parameter "self" to the function is_submitter_human:
>
> ----
> class A(BaseHandler, blobstore_handlers.BlobstoreUploadHandler):
>    def is_submitter_human(self):
>        cResponse = captcha.submit(                     self.request.get('recaptcha_challenge_field').encode('utf-8'),                     self.request.get('recaptcha_response_field').encode('utf-8'),
>                     CAPTCHA_PRV_KEY,
>                     os.environ['REMOTE_ADDR'])
>        return cResponse.is_valid
>
>    def post(self, view):
>        logging.debug('starting recaptcha check')
>        isHuman = self.is_submitter_human()# here I don't pass a parameter
>        logging.debug('recaptcha check isHuman:' +str(isHuman))
>        if not isHuman:#failed captcha and can try again
>            #Reprint the form
>
> --
> It seems unlike other programming languages where the number of arguments in the call are the same as the number of arguments in the function head and python requires me to add one parameter to the function head and I wonder if you call tell me something about the background why?
>
> What's the story of using these parameters that are called "self"?

Some other languages name the analogous parameter "this" instead of
"self", and basically declare it implicitly for you. In both cases,
said variable is used to refer to the object that the current method
is being called on (e.g. if `w` is a list and I do w.append(v), the
list `w` is `self` in the context of the .append() method call). Since
Python's object-orientation is slightly impure, you are required to
declare `self` explicitly in the parameter list, unlike most other
languages. Technically, you are free to name the parameter something
else instead of "self"; naming it "self" is merely a convention.
However, no matter its name, the first parameter to a method will
always receive the current object as its argument value.

So, given: x = Foo()
Then: x.bar(y, z)
is approximately equivalent to:
Foo.bar(x, y, z) # perfectly legal working code

So the number of arguments actually /does/ match the number of
parameters; `x`/`self` is just passed implicitly via the semantics of
the dot (".") operator.

Cheers,
Chris



More information about the Python-list mailing list