2013-06-12 52 views
0

我收到以下错误,当我运行在该行的代码,我打上了#<---类型错误:“的游戏玩家”对象未标化的

TypeError: 'GamePlayer' object is not subscriptable

显然,不可以订阅means I don't have a certain method implemented。我不知道这是如何适用于我的代码,或者如何解决它。第二个函数是错误发生的地方。

传递给该函数的值是:["b'direction:north", 'fromTime:2013-06-12 16:32:27.102400', 'fromY:0', 'fromX:0', "identity:1,'"](我不知道如何摆脱b'),但我确定它不会导致问题。

@staticmethod 
def data_line_to_dict(data): 
    decoded = dict() 
    data_peices = str(data).split(', ') 
    print(data_peices) 
    for d in data_peices: 
     key_val = d.split(':') 
     print(key_val) 
     decoded[key_val[0]] = key_val[1] 
    return decoded 

@staticmethod 
def create_from_data_line(data): #The value of data is: ["b'direction:north", 'fromTime:2013-06-12 16:32:27.102400', 'fromY:0', 'fromX:0', "identity:1,'"] 
    dictionary_data = GamePlayer.data_line_to_dict(data.strip()) 
    p = GamePlayer() 
    p.set_variable('fromX', int(p['fromX'])) #<--- where error occurs 
    p.set_variable('fromY', int(p['fromY'])) 
    date = datetime.datetime.strptime(p['fromTime'], '%Y-%m-%d %H:%M:%S') 
    p.set_variable('fromTime', data) 
    p.set_variable('identity', int(p['identity'])) 
    return p 

def create_data_line(self): 
    final = "" 
    for k in self.values: 
     v = self.values[k] 
     final += str(k) + ":" + str(v) 
     final += ", " 
    return final 

def set_variable(self, variable, value): 
    self.values[variable] = value 

def get_variable(self, variable): 
    return self.values[variable] 

def get_microseconds_in_direction(self): 
    now = datetime.datetime.today() 
    diff = now - self.get_value['fromDate'] 
    return diff.microseconds 
+0

此外,'B'在你的数据是因为你强制转换'bytes'到'str'。使用'data.decode(“utf-8”)'(或者你使用的任何编码)而不是'str(data)',或者用“r”模式而不是“rb”打开文件。 –

回答

1

的问题是,你使用的GamePlayerp['fromX'])的[]操作,但你没有实现它。我假设你打算做p.get_variable("fromX")

我建议不要这样做。刚刚命名它有什么问题p.fromX?你的get_variableset_variable函数只是重新实现Python的基本功能。

+0

*手掌到额头*我意识到我的意思是使它'dictionary_data ['fromX']',但必须意外键入'p'。 –

0

尝试p.values['fromX']p.get_variable('fromX')