Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #12363 > unrolled thread

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

Started byNiklas Rosencrantz <niklasro@gmail.com>
First post2011-08-28 17:26 -0700
Last post2011-08-29 16:15 +1000
Articles 8 — 6 participants

Back to article view | Back to comp.lang.python


Contents

  Why I need the parameter when the call doesn't use it? Niklas Rosencrantz <niklasro@gmail.com> - 2011-08-28 17:26 -0700
    Re: Why I need the parameter when the call doesn't use it? Ben Finney <ben+python@benfinney.id.au> - 2011-08-29 11:32 +1000
    Re: [Python] Why I need the parameter when the call doesn't use it? Chris Gonnerman <chris@gonnerman.org> - 2011-08-28 20:42 -0500
      Re: [Python] Why I need the parameter when the call doesn't use it? Ben Finney <ben+python@benfinney.id.au> - 2011-08-29 12:34 +1000
        Re: [Python] Why I need the parameter when the call doesn't use it? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-08-29 14:40 +1000
    Re: Why I need the parameter when the call doesn't use it? Chris Rebert <clp2@rebertia.com> - 2011-08-28 18:52 -0700
    Re: Why I need the parameter when the call doesn't use it? John Gordon <gordon@panix.com> - 2011-08-29 03:27 +0000
      Re: Why I need the parameter when the call doesn't use it? Ben Finney <ben+python@benfinney.id.au> - 2011-08-29 16:15 +1000

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

FromNiklas Rosencrantz <niklasro@gmail.com>
Date2011-08-28 17:26 -0700
SubjectWhy I need the parameter when the call doesn't use it?
Message-ID<66a3f64c-d35e-40c7-be69-ddf708e37ba7@glegroupsg2000goo.googlegroups.com>
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"?

Thank you

[toc] | [next] | [standalone]


#12369

FromBen Finney <ben+python@benfinney.id.au>
Date2011-08-29 11:32 +1000
Message-ID<87mxett32x.fsf@benfinney.id.au>
In reply to#12363
Niklas Rosencrantz <niklasro@gmail.com> writes:

> I modularize code for a webapp and I want to know what python makes
> that a need to define an argument called self?

Because, when calling a method on an instance, the instance is a
parameter to the call. That is,

    foo = Thribble()
    foo.bar("spam")

is usually syntactic sugar for

    foo = Thribble()
    foo.__class__.bar(foo, "spam")

and so the definition of that function on the Thribble class needs to
accept both parameters.

> 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

Yes, because the code of ‘is_submitter_human’ needs to know *which*
instance has been passed. That instance is bound to the first parameter,
which is conventionally named ‘self’.

> 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?

I hope that explains.

See also:

    <URL:http://docs.python.org/faq/programming.html#what-is-self>
    <URL:http://docs.python.org/faq/design.html#why-self>

-- 
 \      “Nullius in verba” (“Take no-one's word for it”) —motto of the |
  `\                                   Royal Society, since 1663-06-30 |
_o__)                                                                  |
Ben Finney

[toc] | [prev] | [next] | [standalone]


#12371 — Re: [Python] Why I need the parameter when the call doesn't use it?

FromChris Gonnerman <chris@gonnerman.org>
Date2011-08-28 20:42 -0500
SubjectRe: [Python] Why I need the parameter when the call doesn't use it?
Message-ID<mailman.526.1314582221.27778.python-list@python.org>
In reply to#12363
On 08/28/2011 07:26 PM, Niklas Rosencrantz 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):
is_submitter_human() isn't a function, it's a method.  Methods are 
always called with a reference to the class instance (i.e. the object) 
that the method belongs to; this reference is the first argument, and is 
conventionally called "self".

Though I've hacked it out, your code sample includes calls to other 
methods of the object, by calling self.methodname().  Without the first 
parameter, how else would you do it?

-- Chris.

[toc] | [prev] | [next] | [standalone]


#12374 — Re: [Python] Why I need the parameter when the call doesn't use it?

FromBen Finney <ben+python@benfinney.id.au>
Date2011-08-29 12:34 +1000
SubjectRe: [Python] Why I need the parameter when the call doesn't use it?
Message-ID<87fwklt07k.fsf@benfinney.id.au>
In reply to#12371
Chris Gonnerman <chris@gonnerman.org> writes:

> On 08/28/2011 07:26 PM, Niklas Rosencrantz wrote:
> > class A(BaseHandler, blobstore_handlers.BlobstoreUploadHandler):
> >      def is_submitter_human(self):

> is_submitter_human() isn't a function, it's a method.

No, that's not true and may lead to future confusion.

Rather, it is a function *and* a method. Not all functions are methods,
but all methods are functions.

> Methods are always called with a reference to the class instance

Also not true, but perhaps too subtle an issue to explore in this thread.

> Though I've hacked it out, your code sample includes calls to other
> methods of the object, by calling self.methodname(). Without the first
> parameter, how else would you do it?

Yes, that's exactly the reason. Thanks.

-- 
 \         “A child of five could understand this. Fetch me a child of |
  `\                                              five.” —Groucho Marx |
_o__)                                                                  |
Ben Finney

[toc] | [prev] | [next] | [standalone]


#12385 — Re: [Python] Why I need the parameter when the call doesn't use it?

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2011-08-29 14:40 +1000
SubjectRe: [Python] Why I need the parameter when the call doesn't use it?
Message-ID<4e5b1847$0$30004$c3e8da3$5496439d@news.astraweb.com>
In reply to#12374
On Mon, 29 Aug 2011 12:34 pm Ben Finney wrote:

> Chris Gonnerman <chris@gonnerman.org> writes:
> 
>> On 08/28/2011 07:26 PM, Niklas Rosencrantz wrote:
>> > class A(BaseHandler, blobstore_handlers.BlobstoreUploadHandler):
>> >      def is_submitter_human(self):
> 
>> is_submitter_human() isn't a function, it's a method.
> 
> No, that's not true and may lead to future confusion.
> 
> Rather, it is a function *and* a method. Not all functions are methods,
> but all methods are functions.

Wouldn't it be more accurate to say that methods *wrap* functions?

>>> class C(object):
...     def spam(self):
...             pass
...
>>> C().spam
<bound method C.spam of <__main__.C object at 0xb7e975cc>>
>>> C().spam.im_func
<function spam at 0xb7e8c25c>


(At least for pure Python methods... those written in C, such as for the
built-in types, don't.)


>> Methods are always called with a reference to the class instance
> 
> Also not true, but perhaps too subtle an issue to explore in this thread.

But for the record, you have "normal" instance methods, class methods,
static methods, and any other sort of method you can create using the
descriptor protocol, such as this one:

http://code.activestate.com/recipes/577030-dualmethod-descriptor/

But as Ben hints at, this is getting into fairly advanced territory.



-- 
Steven

[toc] | [prev] | [next] | [standalone]


#12372

FromChris Rebert <clp2@rebertia.com>
Date2011-08-28 18:52 -0700
Message-ID<mailman.527.1314582726.27778.python-list@python.org>
In reply to#12363
On Sun, Aug 28, 2011 at 5:26 PM, Niklas Rosencrantz <niklasro@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

[toc] | [prev] | [next] | [standalone]


#12383

FromJohn Gordon <gordon@panix.com>
Date2011-08-29 03:27 +0000
Message-ID<j3f0ul$69h$1@reader1.panix.com>
In reply to#12363
In <66a3f64c-d35e-40c7-be69-ddf708e37ba7@glegroupsg2000goo.googlegroups.com> Niklas Rosencrantz <niklasro@gmail.com> writes:

> What's the story of using these parameters that are called "self"?

"self" is a reference to the class object, and it allows the method to
access other methods and variables within the class.

For example, say you have this class:

  class MyClass(object):

    def method1(self, x):
      self.x = x
      self.say_hello()

    def say_hello(self):
      self.x = self.x + 1
      print "hello"

Without the "self" reference, method1 wouldn't be able to access
instance variable x and it wouldn't be able to call say_hello().

If you have a method that doesn't need to access other variables or
methods within the class, you can declare it with the @staticmethod
decorator.

-- 
John Gordon                   A is for Amy, who fell down the stairs
gordon@panix.com              B is for Basil, assaulted by bears
                                -- Edward Gorey, "The Gashlycrumb Tinies"

[toc] | [prev] | [next] | [standalone]


#12393

FromBen Finney <ben+python@benfinney.id.au>
Date2011-08-29 16:15 +1000
Message-ID<87bov8u4jd.fsf@benfinney.id.au>
In reply to#12383
John Gordon <gordon@panix.com> writes:

> In <66a3f64c-d35e-40c7-be69-ddf708e37ba7@glegroupsg2000goo.googlegroups.com> Niklas Rosencrantz <niklasro@gmail.com> writes:
>
> > What's the story of using these parameters that are called "self"?
>
> "self" is a reference to the class object, and it allows the method to
> access other methods and variables within the class.

No, ‘self’ (in an instance method, which is where it's normally used) is
bound to the instance object. The class object is a different thing.

-- 
 \         “Alternative explanations are always welcome in science, if |
  `\   they are better and explain more. Alternative explanations that |
_o__) explain nothing are not welcome.” —Victor J. Stenger, 2001-11-05 |
Ben Finney

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web