29

Possible Duplicate:
Why do you need explicitly have the “self” argument into a Python method?

I understand why self is always the first argument for class methods, this makes total sense, but if it's always the case, then why go through the hassle of typing if for every method definition? Why not make it something thats automatically done behind the scenes?

Is it for clarity or is there a situation where you may not want to pass self as the first argument?

Community
  • 1
  • 1
jonathan topf
  • 7,897
  • 17
  • 55
  • 85
  • 7
    Note that the term *class method* means something different to what you appear to think it means. A *method* is a function owned by a class, which acts on an instance - a *class method* is a method which is owned by a class, which acts on the class. You are talking about the former (which take ``self`` by convention) as opposed to the latter (which take ``cls`` by convention). – Gareth Latty Oct 14 '12 at 13:03

2 Answers2

36

Because explicit is better than implicit. By making the parameter an explicit requirement, you simplify code understanding, introspection, and manipulation. It's further expanded on in the Python FAQ.

Moreover, you can define class methods (take a class instead of an instance as the first argument), and you can define static methods (do not take a 'first' argument at all):

class Foo(object):
    def aninstancemethod(self):
        pass

    @classmethod
    def aclassmethod(cls):
        pass

    @staticmethod
    def astaticmethod():
        pass
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 18
    I would argue *Because explicit is better than implicit* is an oversimplification. – Gareth Latty Oct 14 '12 at 12:51
  • 5
    @Lattyware: I should have perhaps explained more, but *Explicit is better than implicit* **is** at the core of the Python philosophy. – Martijn Pieters Oct 14 '12 at 13:03
  • 1
    Very much so, and it's an important point here, I would just argue that there are many more (and more important) reasons why this is the way Python works. – Gareth Latty Oct 14 '12 at 13:05
17

Guido explained that here. Basically, methods are functions, and functions should not accept any "hidden" parameters, otherwise higher-order facilities, like decorators, won't be able to deal with them in a sensible way.

georg
  • 211,518
  • 52
  • 313
  • 390