2017-11-17 273 views
0

这个问题被问了很多,但不幸的是我发现没有答案适合我的问题。如果可能的话,我更喜欢一个通用的答案,因为我是一个试图学习Python的新手。先谢谢你。Python - AttributeError:'粒子'对象没有属性'显示'

这是我通过对蟒蛇的使用pygame的图书馆基础下面的教程代码:

import pygame 

background_colour = (255, 255, 255) 
(width, height) = (300, 200) 


class Particle: 
    def __init__(self, x, y, size): 
     self.x = x 
     self.y = y 
     self.size = size 
     self.colour = (0, 0, 255) 
     self.thickness = 1 


screen = pygame.display.set_mode((width, height)) 


def display(self): 
    pygame.draw.circle(screen, self.colour, (self.x, self.y), self.size, self.thickness) 


pygame.display.set_caption('Agar') 
screen.fill(background_colour) 
pygame.display.flip() 

running = True 
my_first_particle = Particle(150, 50, 15) 
my_first_particle.display() 
while running: 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      running = False 

它被用来创建游戏的窗口,里面有一个圆圈。该圆被定义为一个类,以后将以类似的方式多次使用。

我得到了以下错误:

Traceback (most recent call last): 
    File "C:/Users/20172542/PycharmProjects/agarTryout/Agar.py", line 29, in <module> 
    my_first_particle.display() 
AttributeError: 'Particle' object has no attribute 'display' 

什么原理我我不理解,什么是此错误的特定解决方案?

谢谢你的时间和精力。

+1

你的'粒子'类没有定义'display'方法。你是否打算在其他东西上调用'display'?也许'pygame'? – FamousJameous

+0

不确定你在问什么 - 错误很明显。你正在调用一个不存在的方法。 – jhpratt

回答

0

定义的display函数不在Particle中,而是位于脚本的global(不确定此名称是否正确)级别。缩进在python中很重要,因为它没有括号。在您的__init__函数之后移动该功能,并使用相同的缩进。

此外,我想你应该移动screen高于你的Particle的定义。

0

通过您对粒子类的定义,my_first_particle(粒子的一个实例)没有显示属性。

它看起来像显示函数的定义应该是粒子类定义的一部分。

查看Python类教程。

相关问题