【问题标题】:How to access local variables within a class如何访问类中的局部变量
【发布时间】:2019-08-06 06:27:33
【问题描述】:

我正在处理一项任务,并试图访问一个类中的函数内的局部变量。有谁知道如何从类中的函数打印局部变量?我们不允许在类中的函数中打印任何内容,所以我想知道如何做到这一点。

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' object has no attribute '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即可得到:q.tempq.average
  • 根据定义,局部变量在创建它们的函数范围之外是不可访问的。但是,您似乎正在尝试访问实例属性,而不是局部变量。无论如何,您需要提供minimal reproducible example
  • @Tomerikoo 好吧,函数可以具有属性,实际上,它们只是function 类的实例。但是,它们的局部变量不能作为属性神奇地访问,这正是 OP 似乎假设的情况。
  • @Tomerikoo 很可能,当第一次调用时,.active_jobs 会命中if 分支,并且永远不会分配给self.temp。没有minimal reproducible example 就不可能知道,但这是我的猜测
  • @AmanDhaliwal 是的,但请注意,self.temp 仅被分配到两个条件分支之一。所以在.active_jobs被调用后可能就不存在了。

标签: python oop


【解决方案1】:

active_jobs 创建 temp 实例属性。假设实例为q;使用q.temp 访问该属性。

【讨论】:

    最近更新 更多