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#.
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 .
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.
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.
Writing this parameter as self is merely a convention. It is not a keyword and has no special meaning in Python.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With