How to inherit a pygame class?

0

When I run this code (this is the current integer code, ie only 3 lines):

import pygame
class sp(pygame.sprite):
    pass

I get:

  

TypeError: module () takes at most 2 arguments (3 given)

I would like to inherit this class to create some additional objects in it, as well as perform some of the existing functions.

For example, instead of ...

mysprites = pygame.sprite.Group()

I want ...

mysprites = sp.Group()

How can I do this?

    
asked by anonymous 17.09.2018 / 03:42

2 answers

1

You can not create a child class of a module. The inheritance system only works from class to class, and modules are not classes . They are objects, instances of class module .

What you said you want at the end of the question does not need inheritance, it can be done like this:

from pygame import sprite as sp
mysprites = sp.Group()

If you want, for some reason to create a child class of sprite.Group you can, mainly because sprite.Group is a class :

class MyGroup(sp.Group):
    ...
But inherit from a module as I said at the beginning of the answer, it is not something that makes sense in the language.

    
17.09.2018 / 03:51
0

The class you should inherit in Pygame for normal use of the library is pygame.sprite.Sprite - the problem you had was just confusing pygame.sprite which is the module, with pygame.sprite.Sprite being the Sprite class inside of the module.

Inheriting this class and by calling the __init__ method of superclasses, its objects will work with groups and all methods in them, as it is in the documentation.

import pygame
class sp(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
         ...

As for your second question, it is natural to want to shorten what you type, and Python allows this, even with three different forms of the import command.

Instead of

import pygame
a = = pygame.sprite.Group()

you can do:

from pygame.sprite import Group    a = Group ()

or

import pygame.sprite as sp
a = sp.Group()
    
17.09.2018 / 18:39