Skip to main content
 首页 » 编程设计

python之Class Attribute明明是有的,但是python找不到

2025年05月04日15jpfss

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

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' 

请您参考如下方法:

您需要创建一个实例才能像这样使用您的类:

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

在您的代码中,您试图访问 class-level attribute这在你的类(class)中没有定义。