Functions NameError

一世执手 提交于 2019-12-13 01:16:38

问题


I have been messing around with some code, trying to create a function for work planning. However I am stuck and wondered if someone could help? Thanks

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

it comes up with the error: NameError: name 'work_load' is not defined


回答1:


You defined the variable work_load inside the __init__ of the class, so you can't access it outside this scope.

If you want to have access to work_load, make it an attribute for objects of Work_plan class, and the access it by doing object.work_plan

For example:

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


来源:https://stackoverflow.com/questions/30382805/functions-nameerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!