功能NameError(Functions NameError)

2019-10-23 04:12发布

我一直在瞎搞一些代码,试图创建工作规划的功能。 但是我坚持,她想知道如果有人可以帮助? 谢谢

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”没有定义

Answer 1:

您定义的变量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


文章来源: Functions NameError