2011-11-13 39 views
4

我真的想学习班,有什么东西是抱着他们回来,我得到NameError:全球名“自我”是没有定义 - 班

"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() 

回答

3

你不需要实例化类时通过self

Assignment(self, name, discription, deadline, grade, studentID) 

应该

Assignment(name, discription, deadline, grade, studentID) 

的错误是让你知道你正在尝试使用未在本地或全球范围内定义的变种self

6

的问题是在这里:

a = Assignment(self, name, discription, deadline, grade, studentID) 

这是在@staticmethod,所以self没有定义。

的确,这些值都没有被定义,可以想到它 - 除了studentID

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() 
0
在类decleration

class Assignment: 

改变它

class Assignment(): 

class Assignment(object): 
相关问题