Error: "illegal target for variable annotation" using "@property"

2

Because pygame does not have a library-like function SFML - > View , I'm developing a "camera" format to scroll the screen and preserve the positions of the objects within the general coordinate within the "world".

As default for pygame , use rectangle .

For ease of manipulation, I want to change the left and%% variables obtained in get_rect , adding the camera offset to these variables.

Following this example of @jsbueno, I'm having a hard time:

I have a class top and within it I get the rectangle of an image and store class Sprite(pygame.sprite.Sprite) . Hence, I want to return a value other than self.ret = self.imagem.get_rect() every time this variable is accessed.

But by declaring self.ret.left and just below @property I get def ret.left(self): . What would be the correct sitaxe in this case?

import pygame

class Sprite(pygame.sprite.Sprite):
    def __init__(self, imagem, x, y):
        self.imagem = pygame.image.load('imagem.png')
        self.ret = self.imagem.get_rect()

        @property
        def ret.left(self): # aqui aparece o erro 

    
asked by anonymous 02.10.2018 / 23:53

1 answer

2

As I said in the comment the naming funções/métodos does not allow the use of the . character, so the syntax error. What you can do is with the method decorated with @property return the instance of class pygame.Surface.Rect as follows:

import pygame

class Sprite(pygame.sprite.Sprite):

    def __init__(self, imagem, x, y):
        self.imagem = pygame.image.load('imagem.png')
        self._ret = self.imagem.get_rect()

    @property
    def ret(self):
        return self._ret

Allowing self.ret.left to be made, but we do not have any sense, since ret is already an attribute of the self.ret.left instance already accessible. Unless you think of implementing a setter for this attribute, you would then need that getter . An alternative would be:

import pygame

class Sprite(pygame.sprite.Sprite):

    def __init__(self, imagem, x, y):
        self.imagem = pygame.image.load('imagem.png')
        self.ret = self.imagem.get_rect()

    @property
    def ret_left(self):
        return self.ret.left

    @property
    def ret_right(self):
        return self.ret.right
    
03.10.2018 / 01:21