Skip to content
Advertisement

Python AttributeError When Attribute is Set

I am creating a snake clone using pygame and I am running into a strange problem. I have a class called snake_tile that inherits from the pygame rectangle class with one additional attribute, the direction the tile is moving:

JavaScript

I pass in a tuple as the direction when initializing the snake_tile object:

JavaScript

Which will serve as the offset when I move the tile later on, as the pygame.Rect.move() function takes in an x and y offset:

JavaScript

However, when I attempt to move the tile like above I get this error:

JavaScript

But when I try something like this:

JavaScript

I get the output:

JavaScript

So it seems as though the direction attribute is correctly being set, but when I try to access is again to move the snake head I get an attribute error.

Any ideas?

Advertisement

Answer

pygame.Rect.move does not change the rectangle object in place: it creates a new object and returns that new instance.

Although it plays well with inheritance: i.e. it returns a new instance of any subclass, and not a plain Rect, it won’t set the .direction attribute on it.

Your work around is as simple as setting the direction attribute in your subclass’ .move method:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement