How is 'super' used in Python classes and what is it used for?

Asked

Viewed 15,547 times

23

How to use and for what purpose super in classes Python?

  • Look at this blog, I just think it translated on google, but it helps a little: http://livretec.wordpress.com/2014/06/25/super-python/

  • problem solved.

  • @user11802 I just realized that the article you indicated is the Portuguese translation of the article I had included in my reply! : I changed my reply to refer to it - because although it looks like translation via Google, at least it is in the right language...

  • the syntax super(Derivada, self).__init__() can also be used in Python3, right?

  • @beteraba Yes, you can. The two parameters belong to function super and are optional.

1 answer

30


The super serves to - in an inheritance relationship between a class Base and another Derivada - allow the class Derivada refers explicitly to the class Base.

Suppose the following classes:

class Base(object):
    def __init__(self):
        print 'Construindo a classe Base'

class Derivada(Base):
    def __init__(self):
        print 'Construindo a classe Derivada'

x = Derivada()

When this code is executed, only "Building the Derivative class" will be printed on the screen, as the Base was not called at any time. If we want it to be called, we have two alternatives:

  1. Refer to the manufacturer of Base directly:

    class Derivada(Base):
        def __init__(self):
            Base.__init__(self)
    
  2. Use super, allowing the interpreter to find the right superclass for you:

    class Derivada(Base):
        def __init__(self):
            super().__init__()               # Python 3
            super(Derivada, self).__init__() # Python 2
    

The super not only for the constructor, of course: any class method Base can be called this way by the class Derivada:

class Derivada(Base):
    def foo(self, arg): pass
    def bar(self, arg):
        super().foo(arg) # Chama o método foo de Base, não de si própria

Perks

At first glance, there doesn’t seem to be much advantage to using method 2 (with super) regarding method 1 (naming the base class explicitly), except perhaps for the simplest code (in Python 3; in 2, it gets even longer!). But as per that post (just as pointed out by user11802 in the comments), there are situations where the use of super in fact makes quite a difference. Consider for example a subclass of dict register in a log file every time an item is changed:

class LoggingDict(dict):
    def __setitem__(self, key, value):
        logging.info('Setting %r to %r' % (key, value))
        super().__setitem__(key, value)

Suppose we wanted to modify this class to inherit from MeuDict instead of dict. In that case, it would be enough to change the definition of the class:

class LoggingDict(MeuDict):

and everything else would remain the same. If access to the basic methods were explicit, we would have to modify every part that refers to dict to change to MeuDict. In other words, the use of super decoupled the base class and derivative to a certain extent, improving the maintainability of the code.

The linked article has other examples for more complex situations, some involving multiple inheritance (situation where the usefulness of the super becomes more evident).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.