函数NameError

时间:2015-05-21 19:34:53

标签: python nameerror function

我一直在搞乱一些代码,试图为工作计划创建一个功能。但是我被困住了,想知道是否有人可以提供帮助?感谢

class Work_plan(object):
    def __init__(self,hours_work,work_len, work_des):
        self.hours_work = hours_work
        self.work_len = work_len
        self.work_des = work_des

        work_load = []
        hours_worked = []
        if hours_worked > hours_work:
            print "Too much work!"
        else:
            work_load.append(work_des)
            hours_worked.append(work_len)
            print "The work has been added to your work planning!"

work_request = Work_plan(8, 2, "task1")
Work_plan
print work_load

它出现了错误:        NameError:名称'work_load'未定义

1 个答案:

答案 0 :(得分:0)

您在类的work_load内定义了变量__init__,因此您无法在此范围之外访问它。

如果您想要访问work_load,请将其设为Work_plan类对象的属性,并通过object.work_plan

进行访问

例如:

class Work_plan(object):
    def __init__(self,hours_work,work_len, work_des):
        self.hours_work = hours_work
        self.work_len = work_len
        self.work_des = work_des

        self.work_load = []
        self.hours_worked = []
        if hours_worked > hours_work:
            print "Too much work!"
        else:
            self.work_load.append(work_des)
            self.hours_worked.append(work_len)
            print "The work has been added to your work planning!"

work_request = Work_plan(8, 2, "task1")
Work_plan
print work_request.work_load