Python: Initializing members of an object with a parent constructor?

So, I have Python code that structured something like this:

class GameObject(pygame.spriteDirtySprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = None self.rect = None self.state = None class Bullet(gameobject.GameObject): FRAME = pygame.Rect(23, 5, 5, 5) STATES = config.Enum('IDLE', 'FIRED', 'MOVING', 'COLLIDE', 'RESET') def __init__(self): gameobject.GameObject.__init__(self) self.image = config.SPRITES.subsurface(self.__class__.FRAME) self.rect = self.__class__.START_POS.copy() self.state = self.__class__.STATES.IDLE class ShipBullet(bullet.Bullet): START_POS = pygame.Rect(somewhere) def __init__(self): super(bullet.Bullet, self).__init__() self.add(ingame.PLAYER) class EnemyBullet(bullet.Bullet): START_POS = pygame.Rect(somewhere else) def __init__(self): super(bullet.Bullet, self).__init__() self.add(ingame.ENEMIES) 

They are actually located in different files, but this is an inheritance problem, not a dependency problem.

Note that ShipBullet and EnemyBullet have different static START_POS elements, but Bullet does not. Since Bullet will never be created (if it were C ++, I would make it an abstract class), this is intentional. My reasoning is that when I call Bullet.__init__() from my subclasses, the specified subclasses will refer to their own START_POS when they initialize their members. However, this is not the case; ShipBullet.rect (similar to EnemyBullet ) None . I believe image may be None too, but I have not tested this yet. Does any mind help me understand what I'm doing wrong?

+4
source share
1 answer

Use super(EnemyBullet, self).__init__() (and similar for ShipBullet ). super uses the class in the first argument to determine the next base in the MRO.

+2
source

Source: https://habr.com/ru/post/1447636/


All Articles