Re: Confused with methods

From: Matthias Kempka (lists_at_mkempka.de)
Date: 02/06/05


Date: Sun, 06 Feb 2005 17:19:52 +0100
To: python-list@python.org

Hi Gerald,

When you define an instance method, the first parameter (in the
definition) represents the instance. By convention, you would name it
"self":

#####################
class B:
    def foo(self, x):
       print "we have two parameters: " + str(self) + " and " + x
#####################

then calling

######################
b = B()
b.foo("x")
######################

would be equivalent to

######################
b = B()
B.foo(b, "x")
######################

So, as you have noted, you need at least one parameter to attach the
method to an instance. This is because the instance _is_ the parameter.
Python does this for you internally.

For more documentation you should read the paragraph about classes in
the tutorial.

Regards,
Matthias



Relevant Pages

  • Re: Using function parameters to determine method kind
    ... > def outermeth: ... I believe there is a use for a builtin instancemethod descriptor anyways. ... instance method that is always called as an unbound method. ... with 'cls' rather than 'self' as a first parameter. ...
    (comp.lang.python)
  • Re: Decorators: an outsiders perspective
    ... > Because of the conventions widely used (in Python) today, ... > us will assume that that this is an instance method. ... > overloading the semantics of the first parameter. ...
    (comp.lang.python)
  • Re: Scope of an @variable
    ... def changeName ... Each instance variable belongs to one object. ... In the top level of the class definition, ... object, but inside an instance method, it's the instance ...
    (comp.lang.ruby)
  • Re: Decorators: an outsiders perspective
    ... you use 'self' as the name of your first parameter, ... will assume that that this is an instance method. ... If we strive for well written code, we follow these conventions. ... no other even semi-popular languages do this. ...
    (comp.lang.python)
  • why descriptors? (WAS: Make staticmethod objects callable?)
    ... While I wasn't around when descriptors and new-style classes were introduced, my guess is that it's mainly because what you *usually* want when defining a function in a class is for that function to be an instance method. ... def foo: ... With a normal function ... <function foo at 0x00E69530> ...
    (comp.lang.python)