Python - AttributeError: 'Particle' object has no attribute 'display'
Python - AttributeError: 'Particle' object has no attribute 'display'
这个问题被问了很多,但不幸的是我没有找到适合我问题的答案。如果可能的话,我更喜欢一个通用的答案,因为我是一个试图学习的新手 Python。提前谢谢你。
这是我通过使用 pygame 库遵循 python 基础教程得到的代码:
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
用于创建游戏window,里面有一个圆圈。圆圈被定义为 class,稍后将以类似的方式多次使用。
我收到以下错误:
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'
我是什么原理没理解,这个错误的具体解决方法是什么?
感谢您的时间和精力。
定义的 display
函数不在 Particle 内部,而是在脚本的 global
(不确定这个名称是否正确)级别。 python 中的缩进很重要,因为它没有方括号。将函数移到 __init__
函数之后,缩进相同。
此外,我想您应该将 screen
移动到 Particle
定义之上。
根据您对粒子的定义 class,my_first_particle(粒子的一个实例)没有显示属性。
看起来 display 函数的定义应该是 Particle class 定义的一部分。
查看 Python 类 教程。
这个问题被问了很多,但不幸的是我没有找到适合我问题的答案。如果可能的话,我更喜欢一个通用的答案,因为我是一个试图学习的新手 Python。提前谢谢你。
这是我通过使用 pygame 库遵循 python 基础教程得到的代码:
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
用于创建游戏window,里面有一个圆圈。圆圈被定义为 class,稍后将以类似的方式多次使用。
我收到以下错误:
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'
我是什么原理没理解,这个错误的具体解决方法是什么?
感谢您的时间和精力。
定义的 display
函数不在 Particle 内部,而是在脚本的 global
(不确定这个名称是否正确)级别。 python 中的缩进很重要,因为它没有方括号。将函数移到 __init__
函数之后,缩进相同。
此外,我想您应该将 screen
移动到 Particle
定义之上。
根据您对粒子的定义 class,my_first_particle(粒子的一个实例)没有显示属性。
看起来 display 函数的定义应该是 Particle class 定义的一部分。
查看 Python 类 教程。