Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between super() with arguments and without arguments?

I encountered a code which uses the super() method in 2 different ways, and I can't understand what's the difference in the logic.

I'm learning right now the pygame module and I got a task to create a class of a Ball which inherits from Sprite which is a class from the pygame module (if I'm not mistaken).

I encountered this code:

import pygame

class Ball(pygame.sprite.Sprite):

    def __init__(self, x, y):
        super(Ball, self).__init__()

And I can't understand the difference from:

import pygame

class Ball(pygame.sprite.Sprite):

    def __init__(self, x, y):
        super().__init__()

(Argument of super() method)

What is the difference between those code blocks in their logic? Why do I need to pass to super() method arguments? What are those arguments required to be?

like image 663
Jhon Margalit Avatar asked Mar 03 '23 10:03

Jhon Margalit


1 Answers

In Python-3.x you generally don't need the arguments for super anymore. That's because they are inserted magically (see PEP 3135 -- New Super).

The two argument call and the no-argument call are identical if:

  • The first argument is the class in which the method is defined that uses super. In your case it's Ball so the condition is satisfied.
  • and the second argument to super is the first argument of the method. In your case that's self which is the first argument of the method so that condition is also satisfied.

So in your case there's no difference between the two examples!


However there are some rare cases in which you actually need to call super with different arguments (either with 1 or 2 argument/-s). The documentation of super is a good starting point:

>>> help(super)
Help on class super in module builtins:

class super(object)
 |  super() -> same as super(__class__, <first argument>)
 |  super(type) -> unbound super object
 |  super(type, obj) -> bound super object; requires isinstance(obj, type)
 |  super(type, type2) -> bound super object; requires issubclass(type2, type)
 |  Typical use to call a cooperative superclass method:

But I assume your question was mostly about the difference in your example (where there is no difference) and these super calls that require arguments are very rare and quite an advanced topic, so I'll leave them out of this answer.

However there are some resources that might help if you're interested in the differences:

  • Which of the 4 ways to call super() in Python 3 to use?
  • How can I use super() with one argument in python
like image 186
MSeifert Avatar answered Apr 16 '23 20:04

MSeifert