Self / this

From Jonathan Gardner's Tech Wiki
Jump to: navigation, search

In Object-Oriented Programming, methods are usually attached to classes. This allows behavior like:

a.foo()

where foo is a method of the object a.

When a.foo() is invoked, the programmer expects foo() to know something about 'a'. That is, a.foo() would operate on a and b.foo() would operate on b. This is a violation of the attribute-method equivalence proposal of mine, but it is extremely common.

In order to operate on a or b, when foo() is invoked, it has a special parameter or local variable called self or this that can be used to access the invoking object.

In Python, "self" is explicit. The first parameter of a method is always the object it is operating on. For instance:

class A(object):
    def foo(self):
        print self.name

a = A()
a.name = "a"
a.foo() # prints "a"

In other languages, "self" or "this" is implicit, as in Javascript or Java.

If attribute-method equivalence is followed, then all the parameters to the method would have to be explicitly passed. To achieve the same effect, you would have to write:

a.foo(a)

which is what you write if you assigned foo as an attribute rather than a method.