首页 > 解决方案 > 已分配值时出现属性错误

问题描述

当您到达程序打印 6 的部分后,它会给我下面提到的错误。即使正确归因的价值。我希望它在 Mario.x_location 值等于 LifeShroom.x 值时打印 6。然后在那之后,我希望它在按下 w 时将 Mario.x_location 的值增加一。输入 yes 而不是按 enter,然后输入 w 以了解我的意思。我究竟做错了什么?

start = input('say yes: ')

class Mario:
    x_location = 4  #location of you

class LifeShroom:
    x = 4  #location of the object.

if start == 'yes':
  while start == 'yes':
    command = input('')  #press enter here, after you input yes. 

    if command == 'w':
      Mario.x_location += 1 #change Mario.x_location
      print(Mario.x_location,)

    rules = [Mario.x_location == LifeShroom.x,]

    if all(rules):
        LifeShroom = True

    if LifeShroom:
       print(6) #type w again after it prints 6 and you will get the error below. 

我得到的确切错误:

Traceback (most recent call last):
  File "main.py", line 25, in <module>
    rules_8 = [Mario.x_location == LifeShroom.x,
AttributeError: 'bool' object has no attribute 'x'

标签: pythonattributesattributeerror

解决方案


我可以说你正在做一个无限循环。while 循环没有转义。

在第一个 if 语句中,第一个 if ( if command == 'w':) 不运行,而是运行另外两个。在第一个中,它破坏了你的类 ( LifeShroom = True)。但这是真的,所以它会运行第三个。您的变量 LifeShroom 不是一个类,而是一个布尔值(真)。

下一个循环不再有 LifeShroom 类,因此没有 LifeShroom.x 类属性。


推荐阅读