对象没有属性。属性错误:“ FoodSpawner”对象没有属性“ isFoodOnScreen”

时间:2020-01-15 18:21:03

标签: python pygame

我们正在尝试运行一个pygame程序,但得到一个AttributeError。这是我们得到的错误消息,而且他们说的错误在Food Spawner类的第78行。

Traceback (most recent call last):
  File "\\lchs-file01\staff$\Tyson.Friesen\SYSTEM\Desktop\Python Junk File.py", line 120, in <module>
    food_position = food_spawner.spawn_food()
  File "\\lchs-file01\staff$\Tyson.Friesen\SYSTEM\Desktop\Python Junk File.py", line 78, in spawn_food
    if self.isFoodOnScreen == False:
AttributeError: 'FoodSpawner' object has no attribute 'isFoodOnScreen'

这是我们正在尝试运行的代码,对于pygame来说我们还很陌生,因此详细的帮助将非常有用。谢谢。

class FoodSpawner():
   #----------------------sets the food to spawn randomly
    def __init__(self):
        self.position = [random.randrange(1,50)*10], [random.randrange(1,50)*10]
        self.is_food_on_screen = True
   #----------------------
   #----------------------resets food if it spawns of screen
    def spawn_food(self):
        if self.isFoodOnScreen == False:
            self.position = [random.randrange(1,50)*10], [random.randrange(1,50)*10]
            self.is_food_on_screen = True
        return self.position
   #----------------------
    def set_food_on_screen(self,b):
        self.isFoodOnSceen = b

2 个答案:

答案 0 :(得分:2)

据我所知,您正在self.is_food_on_screen = True中设置属性__init__并尝试访问仅在self.isFoodOnScreen中设置的set_food_on_screen

如果您在spawn_food之前调用set_food_on_screen,则会遇到此异常,因为self.isFoodOnScreen尚未作为实例属性存在。

似乎无论您在哪里使用self.is_food_on_screen都想使用self.isFoodOnScreen

答案 1 :(得分:1)

您通过__init__方法创建了self.is_food_on_screen = True,

...

然后尝试设置isFoodOnScreen(在驼峰的情况下,而不是下划线)...

如果您使用相同的名称,我怀疑您的错误将会消失。