简体   繁体   中英

pyright giving out errors on self.rect when a class inherits from pygame.sprite.Sprite

I have a simple Entity class which inherits from pygame.sprite.Sprite like so:

import pygame

class Entity(pygame.sprite.Sprite):
    def __init__(
        self,
        pos: tuple[int, int],
        size: tuple[int, int],
        color: str,
        *groups: pygame.sprite.AbstractGroup,
    ) -> None:
        super().__init__(*groups)
        self.velocity = pygame.Vector2((0, 0))
        self.image = pygame.Surface(size)
        self.rect = self.image.get_rect(topleft=pos)
        self.image.fill(pygame.Color(color))

However, whenever I try to do something with the class's self.rect , pyright emits the following errors: 版权错误

Although the code still runs fine, I was wondering what is the cause of those error messages, and what can I do to prevent them from showing up?

I tried to do 'None checks' ie if self.rect is not None:... on all the blocks emitting that error but I don't think that is a very good solution.

If it matters, I am using pyright on the native neovim LSP.

Any help would be much appreciated!

The first thing I would suggest is to ensure that all sprites are in a group.

entities = pygame.sprite.Group()

Because the error states

"bottom" is not a known member of "None"

we can assume that the inherited 'rect' class variable that you have got from your Entity class has not been passed through properly.

I would try to debug the error by attempting to print out self.rect in the Entity class and then see what the output is, followed by printing out self.rect in the Enemy class.

Also, try removing the None type hint. Which is why it is probably declaring it as none.

Turns out I have to make a pyrightconfig.json file and specify that I want to ignore errors coming from the pygame library in my venv . It's definitely not the best solution but that's one way to stop the errors if you know the code is correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM