Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Self' of python vs 'this' of cpp/c#

Tags:

python

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#.

like image 742
SohamC Avatar asked Mar 20 '14 07:03

SohamC


People also ask

Is self in Python same as this in C++?

The self in Python is equivalent to the self pointer in C++ and the this reference in Java and C#. You must be wondering how Python gives the value for self and why you don't need to give a value for it. An example will make this clear. Say you have a class called MyClass and an instance of this class called MyObject .

Is self in Python the same as this?

Technically both self and this are used for the same thing. They are used to access the variable associated with the current instance. Only difference is, you have to include self explicitly as first parameter to an instance method in Python, whereas this is not the case with Java.

Does self exist in C++?

In some languages, for example C++ and Java, this or self is a keyword, and the variable automatically exists in instance methods. In others, for example Python, Rust, and Perl 5, the first parameter of an instance method is such a reference.

Is self special in Python?

Writing this parameter as self is merely a convention. It is not a keyword and has no special meaning in Python.


1 Answers

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.

like image 191
Kiwi Avatar answered Sep 23 '22 13:09

Kiwi