【问题标题】:Python - AttributeError: 'Particle' object has no attribute 'display'Python - AttributeError:“粒子”对象没有属性“显示”
【发布时间】:2018-05-01 19:32:11
【问题描述】:

这个问题被问了很多,但不幸的是我没有找到适合我的问题的答案。如果可能的话,我更喜欢一个通用的答案,因为我是一个试图学习 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

它用于创建一个游戏窗口,其中有一个圆圈。圆圈被定义为一个类,以后会以类似的方式多次使用。

我收到以下错误:

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'

我不明白什么原理,这个错误的具体解决方法是什么?

感谢您的时间和精力。

【问题讨论】:

  • 您的 Particle 类没有定义 display 方法。你的意思是打电话给display 吗?也许pygame
  • 不确定您要问的是什么 - 错误很明显。你正在调用一个不存在的方法。

标签: python object attributes attributeerror


【解决方案1】:

定义的display 函数不在粒子内部,而是在脚本的global(不确定这个名称是否正确)级别。缩进在 python 中很重要,因为它没有括号。将函数移到 __init__ 函数之后,缩进相同。

另外,我想您应该将screen 移到您的Particle 定义之上。

【讨论】:

    【解决方案2】:

    根据您对 Particle 类的定义,my_first_particle(Particle 的一个实例)没有显示属性。

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

    查看 Python 类教程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      • 2018-11-19
      • 1970-01-01
      相关资源
      最近更新 更多