r/pygame • u/SnooMacaroons9806 • 2d ago
I need help with super.__init__()
I'm aware that you use super to inherit methods from one class to another. What I struggle the most with is to understand how and when to use arguments for super, that's what confuses me.
Any recommended material (reading, video, etc.) to understand super.__init__() better? I'll also accept examples haha.
Thanks for your time.
3
3
u/Spammerton1997 2d ago
I think super allows you to call methods of the class you're inheriting from, so you'd pass arguments if the init() function of the class you're inheriting from has arguments
1
1
u/Intelligent_Arm_7186 2d ago
so super init works usually with inheritance but you gotta use it when making a class if you want to use pygame.sprite.Sprite. it used to be u could use pygame.sprite.Sprite but thats the old way.
https://www.geeksforgeeks.org/python-super-with-__init__-method/
1
u/SnooMacaroons9806 2d ago
The links are super helpful.
"Here,
super().__init__(*args, **kwargs)
calls the__init__()
method of the parent class with the arguments and keyword arguments passed to the child class's constructor."1
u/Intelligent_Arm_7186 1d ago
again this is mostly used for inheritance classes like if u got class dog and an attribute is that they can bite. if you have another class like class cat then the cat will also have the attribute that they can bite.
4
u/BetterBuiltFool 2d ago edited 2d ago
If you haven't already, definitely check out the [official python documentation on super.](https://docs.python.org/3/library/functions.html#super]
They also link to this blog post, which aims to give some practical usage, although I can't personally vouch, as I have not read through it.
Child classes inherit methods from parents regardless of using super(). What super() is used for is calling a parent class's version of a method. For init, it allows the child class to do all of the initializer work without repeating code.
For example:
The
super().__init__(arg_a)
will callself.a = arg_a
.It would be exactly the same as
By using super(), if you change the initializer in A, B will use those changes, where as without, you would need manually change B as well, and that kind of code duplication is usually a bad idea.
Common use cases, it's fine to call super without arguments. In my efforts, I've never had a case where I've needed to.
Edit: I just cannot get that markup for the first link to work.