[Fixed]-Use of python super function in django model

41👍

super(Snippet, self) causes Python to look in the MRO of the class of self (i.e. self.__class__.mro() for the next class listed after Snippet. It returns a super object which acts as a proxy for that class. That is, calling a method on the super object acts like calling that method on the class.

super(Snippet, self).save(...) calls that class’s save method, with self bound to the first argument.

So super(Snippet, self).save(...) will not call Snippet‘s save method; it will call some other class’s save method. It is tempting to think this “other class” is the “parent class” or “superclass” of Snippet, that is,
models.Model, but that may not be true and it is absolutely wrong to apprehend super this way. Which class super(Snippet, self) ultimately represents depends on self and in particular its class’s MRO.

A very good description of the MRO and super (complete with pictures!) can be found here.

👤unutbu

4👍

I won’t explain again what unutbu explained on super classes, however you obtain the same effect with the following code :

models.Model.save(self, force_insert, force_update)

This is NOT a better way to write it since, if you come to change the class inheritance by adding an intermediate class between Model and Snippet you would also have to change this line (which you would most likely forget). Anyway it’s a good thing to know.

I can also add that the super instruction only works if the class you inherit from extends from object, otherwise you get an exception.

Leave a comment