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

我非常喜欢Python的OOP概念,所以我想知道Python的self功能与CPP / C# this关键字的功能类似。


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.


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. Eg it is explicitly present in method declarations. And method calls executed on the instance of object being called must be executed explicitly using self .

Ie:

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

链接地址: http://www.djcxy.com/p/55148.html

上一篇: 如何从main调用一个类的函数

下一篇: python vs'this'的cpp / c#'Self'