【问题标题】:How to fix this AttributeError如何修复此 AttributeError
【发布时间】:2019-08-07 08:11:52
【问题描述】:

我正在尝试访问类中函数内的变量并打印它。每当我尝试时,我都会不断收到错误消息:AttributeError: 'NoneType' object has no attribute 'job_ID'。

def driver():
    q = my_queue.Queue_()
    for line in df:
        if 'received' in line:
            q.enqueue(line)
            print("Adding job " + q.new_item.job_ID + " to the queue with the timestamp: " + q.new_item.time_stamp + ".")
            print("The prority of the job is: " + q.new_item.job_priority)
            print("The job type is: " + q.new_item.job_type)
        if 'respond' in line:
            q.dequeue()
            print("Completed job " + q.current.job_ID + " in " + str(int(q.time_elapsed)) + " seconds.")
        if 'active' in line:
            q.active_jobs()
            print("Total number of jobs: " + str(len(q.temp)))
            print("Average priority: " + str(q.average))
        if 'modify' in line:
            q.modify(line)
            print("Modified job " + q.current.job_ID)

错误来自此代码中的最后一个打印语句。

这是这里使用的类中的函数:

def modify(self, x): # need to fix printing bug
        self.current = self.head
        while self.current != None:
            if x[1] in self.current.get_data():
                self.current.data[2] = x[2]
                self.current.data[3] = x[3]
                break
                # print("Modified job " + current.job_ID)
            else:
                # print('The job details cannot be modified.')
                pass
            self.current = self.current.get_next()

【问题讨论】:

    标签: python oop


    【解决方案1】:

    您提供的modify函数中循环的退出条件是self.current == None

    当您在最后一个条件语句中调用 modify() 时:

    if 'modify' in line:
            q.modify(line) // here
            print("Modified job " + q.current.job_ID)
    

    您正在使q.current 评估为None。因此,您得到AttributeError 的原因是因为q.currentNone,它没有称为job_ID 的这种属性。

    要解决您的问题,在打印q.current.job_ID 之前,您必须确保q.current 不是None。除此之外,我无法为您提供任何帮助,因为我不知道您的程序的目的是什么。

    【讨论】:

    • while 循环的条件为while self.current != None,所以我们知道当modify() 完成运行时,self.currentNone。由于您在变量q 上调用modify() 方法,因此q.current 将是None
    • 由于没有任何代码行明确地使self.current 计算为None,因此必须是.get_next() 方法使self.current == None
    猜你喜欢
    • 2011-12-30
    • 2015-07-13
    • 2019-12-10
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    相关资源
    最近更新 更多