Is there any advantage in an explicit self instead of the implicit "this"?

15

Unlike most of the [most popular] object-oriented languages that use a keyword to refer to the object that is "target" of a method call (usually called this ), the Python language requires that every method has an additional parameter (the first, and conventionally called self ) to represent that object. This seems like a case of code boilerplate , which you have to always write but does not add a lot of things ...

(Note: this is a particular case of the use of "pronouns" in the code, something possible in the Lisp language in Lisp and extensively used in the Perl language )

There is some concrete reason for not using an implicit this

  • ... or that a method is transformed into a normal function by a reverse operation:

    var foo = {
        bar:function(a, b) {
            return this.x + a + b;
        }
    };
    
    var bar = foo.bar;
    var foo2 = { x:10 };
    bar.call(foo2, 20, 30); // O método original mantém o this explícito,
                            // mas ainda podemos atribuí-lo explicitamente
    
  • So, I see no reason to make explicit the self , just unnecessary code ... Is there any strong argument in favor, perhaps coming from the author (s) of the Python language itself? (or another language that uses similar strategy)

        
    asked by anonymous 08.02.2014 / 09:29

    3 answers

    6

    One of the advantages of using explicit self is that you simplify the language:

    • With explicit self the scope of the self will be a lexical scope equal to that of all other variables. You do not need to create a separate pro-self scope rule.

    • With explicit self, methods and functions are the same thing. With implicit self, functions and methods behave differently.

    • With self explicit, it is easier to know how to call the method of an object with the self of another object (just pass another value in the first parameter). In languages with the most magical self you need to call the function in a special way: in Javascript you have to use call , in Python you will have to be careful not to create a bound method, etc.

    • >

    An example that I think is worth adding to the discussion is the Lua language. There objects are half that hash tables and methods are simply properties of an object that happen to be a function (similarly to Javascript). Unlike Javascript, there is no magic to set the self: By convention, you must call the method by passing the object itself as the first parameter.

    local my_obj = {}
    my_obj.x
    my_obj.my_method = function(self)
      print(self.x)
    end
    
    my_obj.my_method(my_obj)
    
    The disadvantage of the explicit self is the verbosity of this convention, but it may be simpler to solve this with a bit of syntactic sugar than by changing the basic rules of language. For example, in Lua there are some syntactic sugars involving : :

    -- Esse código vai ser desassucarado pra algo parecido
    -- com o exemplo anterior
    
    local my_obj = {}
    my_obj.x = 17
    function my_obj:my_method()
      -- Aqui o ':' insere um parâmetro self no começo da lista de parâmetros
      return self.x
    end
    
    -- Aqui o ':' passa o objeto como primeiro parâmetro na chamada
    -- da função.
    my_obj:mymethod()
    
        
    09.02.2014 / 08:21
    5

    In my opinion, the biggest advantage of the explicit self is to enable closures without getting caught and without special treatment. Of face avoids that problem in which every beginner Javascript falls:

    Objeto.prototype.metodo = function ()
    {
        var self = this;
        setTimeout(function () {
            this.bla(); // errado, this será window
            self.bla(); // correto
        }, 250);
    }
    

    In Python the equivalent would be more or less:

    class Objeto:
     def metodo(self):
      def closure():
       self.bla()
      glib.timeout_add(250, closure)
    

    There is no ambiguity with the explicit 'self', whereas an implicit 'self' could be quite confusing in case there is more nesting of methods.

        
    09.02.2014 / 04:41
    4

    Certainly it would be possible for self to be an implicit parameter, such as this of other languages, but I believe this is because one of the philosophies of Python is to make things explicit.

    Within a Python class, the difference between a method with and one without self is almost the same between a normal method and a static method in languages such as C ++ and Java. In C ++ and Java the this is an implicit parameter in the normal methods, and you have to mark the method as static if you want a static method. In Python this gets completely flawed.

    This also forces you to qualify access to the class attributes. In C ++ and Java, if you see a variable in the middle of a method you do not know if it is a member of the class or not. You can qualify with this to make this explicit, but it is optional. In Python this is always explicit by design.

        
    08.02.2014 / 10:46