Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NameError: global name 'self' is not defined -Classes

Tags:

python

class

i`m trying to learn classes, and something is holding em back, i get

"NameError: global name 'self' is not defined"

the same happens to each class field. can you help me find what am i doing wrong thank you

Code:

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()
like image 490
Bogdan Maier Avatar asked Dec 21 '22 06:12

Bogdan Maier


2 Answers

The problem is here:

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

This is in a @staticmethod, so self isn't defined.

Indeed, none of those values are defined, come to think of it -- except studentID.

like image 51
senderle Avatar answered Jan 02 '23 16:01

senderle


You don't need to pass self when instantiating your class.

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

should be

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

The error is letting you know you are trying to use a var self that is not defined in either local or global scope.

like image 44
Adam Wagner Avatar answered Jan 02 '23 16:01

Adam Wagner