我使用的构造函数 __init__ 错了吗?

Am I using the constructor __init__ wrong?

我有一个 class 试图创建一个实例,然后将其定义为精灵,但它也允许该实例具有其他变量(这是我在 atari breakout 上的后续进展我问了另一个问题的游戏 .)

Just a side note (probably not explained very well, sorry): I originally had all my attributes annexed to a 'brick' attribute:

self.brick = pygame.sprite.Sprite() # the .brick is now a sprite

because I thought it would be impossible to give a sprite user invented attributes such as self.brick.hardness so I did this instead:

self.hardness = 1 # the object has another attribute not interfering with the sprite

This created some conflicts with my sprite collision engine (long story short; the .brick attribute could not call the method blockType since it is not an instance of that class), so I just decided to make the actual instance a sprite, and this might be causing some conflicts with its ulterior attributes.

精灵是通过__init_构造函数创建的,其他属性只有在调用适当的方法时才添加。

class Block:        
    def __init__ (self):
        self = pygame.sprite.Sprite()
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface([width, height])
        self.rect = self.image.get_rect()
    def blockType (self, hardness):
        self.hardness = hardness
        if self.hardness == 1:
            self.image.fill (RED)

block = Block () # These parenthesis might be wrong here
block.blockType (1)

现在这个问题可能又是继承引起的,但是当我创建实例时,一切都很好。但是,当我尝试调用该方法时,出现错误:

AttributeError: 'Block' object has no attribute 'image'

我认为这很奇怪,因为对象在仅通过 运行 构造函数方法创建后应该具有图像属性(如果我不调用该方法,我实际上完全有能力绘制这些屏幕上的精灵,因此它们在技术上确实存在)。我已经尝试解决这个问题,但在这一点上我完全不知道出了什么问题。

如果您需要更多信息,请告诉我,我会更新。

使用此代码时

class Block:        
    def __init__ (self):
        self = pygame.sprite.Sprite() # don't overwrite self here
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface([width, height])
        self.rect = self.image.get_rect()

你用 Sprite 的新实例覆盖 self(这是对新创建的 Block 实例的引用);该实例迟早会被删除,因为您没有保留它的引用。

我猜你的意图是继承 Sprite(这在使用 pygame 时很常见),所以你必须使用:

class Block(Sprite):        
    def __init__ (self):
        super().__init__()
        self.image = pygame.Surface([width, height])
        self.rect = self.image.get_rect()

现在 BlockSprite 的子类,具有 imagerect 属性。