0

Possible Duplicate:
Python 'self' keyword

In Python, instance methods must have the instance passed to them as an argument, like:

class Foo:
    def bar(self):
         print self.name

What's the purpose of making this explicit? (Is it simply implicit < explicit?) In what circumstances would you would want to do pass something other than "self"?

Community
  • 1
  • 1
futuraprime
  • 5,468
  • 7
  • 38
  • 58
  • I think you could call it whatever you want, it's just `self` by convention. However, when you make the method call, python implicitly passes the receiving object as the first argument. – jpm Oct 05 '12 at 23:02
  • Check out the second answer in the answer that @Lattyware linked to – ernie Oct 05 '12 at 23:06
  • Yes, that second answer is pretty much what I was looking for. Thanks! – futuraprime Oct 05 '12 at 23:10
  • Also, see [this question](http://stackoverflow.com/questions/11794918/confusion-on-python-class) where I linked to an [article by GvR explaining it in more detail](http://neopythonic.blogspot.ch/2008/10/why-explicit-self-has-to-stay.html). – phant0m Oct 05 '12 at 23:13

1 Answers1

1

A Python instance method is just a function that is bound to the instance. When called the instance always passes itself as the first argument.

The name self is just a convention. You can call it anything you want. So you could do this:

class Foo:
    def bar(s):
         print s.name

But don't, because it breaks convention. :)

jathanism
  • 33,067
  • 9
  • 68
  • 86
  • 1
    Yes, I get that it can be anything. I'm just curious why it was implemented this way, instead of just being a property of instance methods that they have access to the instance (as in other implementations of class-based inheritance). – futuraprime Oct 05 '12 at 23:05
  • 1
    @futuraprime The answer is because a Python instance method is just a function that is bound to the instance. There is no way that could be true and not have the instance as a parameter. – Marcin Oct 05 '12 at 23:08