python - 如何访问类中的局部变量
问题描述
我正在处理一项任务,并试图访问一个类中的函数内的局部变量。有谁知道如何从类中的函数打印局部变量?我们不允许在类中的函数内打印任何内容,所以我想知道如何做到这一点。
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.active_jobs.temp)))
print("Average priority: " + str(q.active_jobs.average))
我正在尝试打印最后两行,但这就是发生错误的地方。我得到的错误是:AttributeError:'function'对象没有属性'temp'。
这是类中的函数:
def active_jobs(self):
if self.head == None:
pass
# print("No Jobs Available. ")
else:
current = self.head
self.temp = []
while current:
self.temp.append(current.get_data())
current = current.get_next()
return self.temp
# print("Total number of jobs: " + str(len(self.temp)))
self.priority = []
for i in range(len(self.temp)):
self.priority.append(self.temp[i][2])
x = [int(i) for i in self.priority]
self.average = sum(x) / len(x)
return self.average
解决方案
active_jobs
创建temp
实例属性。假设实例是q
; 使用 访问该属性q.temp
。