我正在努力学习课程,有些事情正在重新开始,我得到了
"NameError: global name 'self' is not defined"
每个类字段都会发生同样的情况。你能帮我找到我做错了什么吗谢谢
代码:
class Assignment:
def __init__(self, name, discription, deadline, grade, studentID):
self.name = name
self.studentID = studentID
self.description = discription
self.deadline = deadline
self.grade = grade
def __str__(self):
return "studentID:" + self.studentID + "assignment name:" + self.name +" description:" + self.description + " deadline:" + self.deadline + " grade:" + self.grade
def validation(self):
errors= []
if self.studendID == "":
errors.append("No existing student ID.")
if self.description == "":
errors.append("No existing description.")
if self.deadline == "":
errors.append("No existing deadline.")
if self.deadline == "":
errors.append("No existing deadline.")
return errors
@staticmethod
def dummyAssignments():
ret = []
for studentID in range(100, 121):
print "sda"
a = Assignment(self, name, discription, deadline, grade, studentID)
ret.append(a)
return ret
def testAssigment():
a = Assignment("","","","","")
print a
testAssigment()
print Assignment.dummyAssignments()
答案 0 :(得分:6)
问题在于:
a = Assignment(self, name, discription, deadline, grade, studentID)
这是@staticmethod
,因此self
未定义。
实际上,除了studentID
之外,没有定义这些值,只考虑它 -
答案 1 :(得分:3)
在实例化课程时,您无需传递self
。
Assignment(self, name, discription, deadline, grade, studentID)
应该是
Assignment(name, discription, deadline, grade, studentID)
错误告诉您,您正在尝试使用未在本地或全局范围内定义的var self
。
答案 2 :(得分:2)
dummyAssignments 静态方法只有studentID,但没有任何其他字段。
尝试为每个字段提供默认值:
class Assignment:
def __init__(self, name='', discription='', deadline='', grade='', studentID =''):
self.name = name
self.studentID = studentID
self.description = discription
self.deadline = deadline
self.grade = grade
def __str__(self):
return "studentID:" + self.studentID + "assignment name:" + self.name +" description:" + self.description + " deadline:" + self.deadline + " grade:" + self.grade
def validation(self):
errors= []
if self.studendID == "":
errors.append("No existing student ID.")
if self.description == "":
errors.append("No existing description.")
if self.deadline == "":
errors.append("No existing deadline.")
if self.deadline == "":
errors.append("No existing deadline.")
return errors
@staticmethod
def dummyAssignments():
ret = []
for studentID in range(100, 121):
print "sda"
a = Assignment(studentID=studentID)
ret.append(a)
return ret
def testAssigment():
a = Assignment("","","","","")
print a
testAssigment()
print Assignment.dummyAssignments()
答案 3 :(得分:0)
在你的课堂上宣布:
class Assignment:
将其更改为
class Assignment():
或
class Assignment(object):