Python Snake对象没有属性';rect';?
我有一个snake对象,并在draw方法中定义了self.rect。但是当我引用snake.rect时,它说它没有属性rect。有人知道为什么吗? 蛇类:Python Snake对象没有属性';rect';?,python,pygame,Python,Pygame,我有一个snake对象,并在draw方法中定义了self.rect。但是当我引用snake.rect时,它说它没有属性rect。有人知道为什么吗? 蛇类: class Snake: def __init__(self, x, y): self.x = x self.y = y self.width = 25 self.height = 25 self.direction = 1 self.k
class Snake:
def __init__(self, x, y):
self.x = x
self.y = y
self.width = 25
self.height = 25
self.direction = 1
self.kill = False
self.collide = False
def draw(self):
self.rect = pygame.Rect(self.x, self.y, self.width, self.height)
pygame.draw.rect(screen, BLACK, self.rect)
def events(self):
# change direction on key press
self.keys = pygame.key.get_pressed()
if self.keys[pygame.K_UP]:
self.direction = 1
if self.keys[pygame.K_DOWN]:
self.direction = 3
if self.keys[pygame.K_LEFT]:
self.direction = 4
if self.keys[pygame.K_RIGHT]:
self.direction = 2
if self.rect.colliderect(food.rect):
self.collide = True
print(self.collide)
谢谢
class Test():
def __init__(self, x, y):
self.x = x
self.y = y
self.text = 'Hello world!'
def another_function(self, parameter):
self.variable = parameter
让我们看看这个简单的代码。类实例化后,X和Y将立即初始化,以便:
new_instance = Test(4,5)
print(new_instance.text)
会有用的。
然而
将不起作用,因为变量
尚未绑定到类实例。一旦你这样做了:
new_instance.another_function(3)
print(new_instance.variable)
它会工作。在尝试访问它之前,您需要调用
draw
方法。直接在init中指定self.rect
。@Dschoni,谢谢,但现在蛇不动了。知道为什么吗?@legoroj,哦,是的,我要加入init方法,但它现在不动了。您知道为什么吗?您只显示def代码,而不显示调用代码。这使得很难提供帮助。如其他注释中所述,只有在实际调用draw
方法时才会创建属性。在此之前尝试引用该属性将引发错误
new_instance.another_function(3)
print(new_instance.variable)