【问题标题】:Class Attribute is clearly there, but python cant find it类属性明明有,python却找不到
【发布时间】:2014-01-11 04:53:29
【问题描述】:

为什么我会收到此属性错误?

class GameState(object):
  """Keeps track game state variables"""
  def __init__(self, convo_flag=0, characters_talked_to=0, convo_log=(None)):
    self.convo_flag = convo_flag
    self.characters_talked_to = characters_talked_to
    self.convo_log = convo_log

def welcome_screen():
  global LAST_NAME
  global BULLY
  global DAY

  raw_input(messages.WELCOME)

  LAST_NAME = raw_input(messages.LAST_NAME)
  BULLY = characters.random_character(cclass='Camper', gender='m')

  print 'Your name is Pickett %s' % LAST_NAME

  messages.print_messages([
    messages.EXPLANATION,
    messages.BUS_LOADING,
    messages.CRACK,
    messages.GAME_KID_LOST])

  return week_one(DAY)

def week_one(day):
  if day == 1:
    messages.print_messages(messages.WEEK_ONE[day])
    campers = characters.random_character_sample(cclass='Camper', count=5)
    people_outside_theater = campers + [characters.TROID]

    while GameState.characters_talked_to != 3:

我不明白为什么我得到这个属性错误,我完全在那个构造函数中声明了它,我是否需要在构造函数之外声明它?这真是绞尽脑汁。

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pickett.py", line 44, in welcome_screen
    return week_one(DAY)
  File "pickett.py", line 52, in week_one
    while GameState.characters_talked_to != 3:
AttributeError: type object 'GameState' has no attribute 'characters_talked_to'

【问题讨论】:

  • 如果它“真的”在那里,那么 Python 会找到它。小心断言,练习用更中性的语气写标题/问题。 (“类属性”和“[对象]数据属性”也是不同的..)

标签: python class object attributeerror


【解决方案1】:

您需要创建一个实例,按顺序使用如下类:

gameState = GameState()
while gameState.characters_talked_to != 3:

在您的代码中,您正在尝试访问class-level attribute,在您的类中未定义。

【讨论】:

  • 我做了这些变化,但我仍然得到完全相同的错误!那个赌徒没有一个名为yada yada yada span>的属性
  • 这是我的错误编辑,我做了一个新的一个来反映我的代码的当前状态。 span>
  • 有效!我的坏,忘了我需要重新加载模块,仍然是一个Python noob,非常感谢大家! span>
【解决方案2】:

您的__init__ 函数将characters_talked_to 设置为self,这是GameState 的一个实例。

你没有在GameState上设置它,这是一个类。

您也没有创建任何GameState 的实例,因此无论如何您的程序都不会调用__init__

【讨论】:

    猜你喜欢
    • 2017-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多