设置属性时Python AttributeError
我正在使用Pygame创建一个蛇克隆,并且遇到了一个奇怪的问题。我有一个名为snake_tile的类,它从pygame矩形类继承,带有一个附加属性,瓷砖正在移动的方向:
import pygame
class snake_tile(pygame.Rect):
def __init__(self, left, top, width, height, direction):
super().__init__(left, top, width, height)
self.direction = direction
我在初始化snake_tile对象时将元组作为方向传递为方向:
snake_head = snake_tile(snake_tile_x, snake_tile_y, 10, 10, (0,0))
当我移动瓷砖时,它将用作偏移量稍后,随着pygame.rect.move()函数的x和y偏移量:
snake_head = snake_head.move(snake_head.direction[0], snake_head.direction[1])
但是,当我尝试像上面一样移动瓷砖时,我会遇到此错误:
AttributeError: 'snake_tile' object has no attribute 'direction'
但是当我尝试这样的事情时:
print(snake_head.direction)
snake_head = snake_head.move(snake_head.direction[0], snake_head.direction[1])
我得到输出:
(0, 0)
AttributeError: 'snake_tile' object has no attribute 'direction'
因此,似乎正确设置了方向属性,但是当我尝试访问时,再次移动蛇头时,我会得到属性错误。
有什么想法吗?
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:
import pygame
class snake_tile(pygame.Rect):
def __init__(self, left, top, width, height, direction):
super().__init__(left, top, width, height)
self.direction = direction
I pass in a tuple as the direction when initializing the snake_tile object:
snake_head = snake_tile(snake_tile_x, snake_tile_y, 10, 10, (0,0))
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:
snake_head = snake_head.move(snake_head.direction[0], snake_head.direction[1])
However, when I attempt to move the tile like above I get this error:
AttributeError: 'snake_tile' object has no attribute 'direction'
But when I try something like this:
print(snake_head.direction)
snake_head = snake_head.move(snake_head.direction[0], snake_head.direction[1])
I get the output:
(0, 0)
AttributeError: 'snake_tile' object has no attribute 'direction'
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
pygame.Rect.move
不更改到位的矩形对象:它创建一个新对象并返回该新实例。尽管它具有继承功能:IE返回任何子类的新实例,而不是普通的
rect
,但它不会在其上设置.Direction
属性。您的工作就像在子类中设置方向属性一样简单。
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: