3

I'm fairly new to python and I'm reading a book about creating games with pygame. I came across this piece of code in the book. I don't understand why Sprite.__init__(self) is necessary. I have run the code with this commented out and it runs the same way.

class Creep(Sprite):

    def __init__(   
            self, screen, img_filename, init_position, 
            init_direction, speed)

        Sprite.__init__(self)

        self.screen = screen
        self.speed = speed
        self.base_image = pygame.image.load(img_filename).convert_alpha()
        self.image = self.base_image

Anybody have any idea why this is there and why people call init?

omz
  • 53,243
  • 5
  • 129
  • 141
  • It's just a special method that acts as the constructor for instantiating a class object. (There's even a constructor for creating a class) You don't need it if you don't want to. ``self`` is just a convention name to say ``this``. Think of it this way, class methods like ``__init__`` needs a reference of itself and the first argument will always be ``self``. There is an exception though: staticmethod in a class. But let's not get there until you understand the init and self purpose. – CppLearner May 01 '13 at 08:11
  • `Sprite(self)` would achieve the same thing as `Sprite.__init__(self)` yet create an instance to do so. This usage is a little bit strange as it's calling the `__init__` method without taking the resulting instance. – mfitzp May 01 '13 at 08:24
  • Just noticed the `class Creep(Sprite):` - it looks as though this is equivalent to doing `super(Creep, self).__init__()` on the current class. – mfitzp May 01 '13 at 08:28
  • 2
    Not a duplicate, OP isn't asking what the `__init__` method is, he's asking why `Sprite.__init__` is called within it. – Daniel Roseman May 01 '13 at 08:42

1 Answers1

1

This is calling the superclass initialization method. Presumably, Sprite does some initialization that you would also need in the subclass, and in Python you need to explicitly call that.

Normally, however, you would do it via a call to super:

super(Creep, self).__init__()
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Ok. I think I have a vague idea of whats going on. The class Creep also needs access to certain variables contained within the Sprite object's initialization call? Forgive me if my lingo is a little off. Very new to programming. – Zorion Bakar May 02 '13 at 20:44