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?
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:
super
. In your case it's Ball
so the condition is satisfied.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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With