18

I am quite amateur in OOP concepts of python so I wanted to know are the functionalities of self of Python in any way similar to those of this keyword of CPP/C#.

SohamC
  • 2,367
  • 6
  • 22
  • 34

2 Answers2

14

self & this have the same purpose except that self must be received explicitly.

Python is a dynamic language. So you can add members to your class. Using self explicitly let you define if you work in the local scope, instance scope or class scope.

As in C++, you can pass the instance explicitly. In the following code, #1 and #2 are actually the same. So you can use methods as normal functions with no ambiguity.

class Foo :
    def call(self) :
        pass

foo = Foo()
foo.call() #1
Foo.call(foo) #2

From PEP20 : Explicit is better than implicit.

Note that self is not a keyword, you can call it as you wish, it is just a convention.

Kiwi
  • 2,698
  • 16
  • 15
4

Yes they implement the same concept. They serve the purpose of providing a handle to the instance of class, on which the method was executed. Or, in other wording, instance through which the method was called.

Probably someone smarter will come to point out the real differences but for a quite normal user, pythonic self is basically equivalent to c++ *this.

However the reference to self in python is used way more explicitly. E.g. it is explicitly present in method declarations. And method calls executed on the instance of object being called must be executed explicitly using self.

I.e:

def do_more_fun(self):
  #haha
  pass

def method1(self, other_arg):
  self.do_more_fun()

This in c++ would look more like:

void do_more_fun(){
  //haha
};

void method1(other_arg){
  do_more_fun();
  // this->do_more_fun(); // also can be called explicitly through `this`
}

Also as juanchopanza pointed out, this is a keyword in c++ so you cannot really use other name for it. This goes in pair with the other difference, you cannot omit passing this in c++ method. Only way to do it is make it static. This also holds for python but under different convention. In python 1st argument is always implicitly assigned the reference to self. So you can choose any name you like. To prevent it, and be able to make a static method in python, you need to use @staticmethod decorator (reference).

Community
  • 1
  • 1
luk32
  • 15,812
  • 38
  • 62
  • 1
    Also the name `self` is a convention in python, whereas `this` is a keyword in C++. And most of the time you can omit `this` (in C++, C# may be more verbose.) – juanchopanza Mar 20 '14 at 07:33