2011-11-13 65 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): 
相關問題