Why always add self as first argument to class methods?

jonathan topf picture jonathan topf · Oct 14, 2012 · Viewed 18.6k times · Source

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?

Answer

Martijn Pieters picture Martijn Pieters · Oct 14, 2012

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