Wassim Gr Wassim Gr - 11 days ago 5
Python Question

Object has no attribute questionNum

I am not sure if I fully understand class/instance variables. I have this code :

class Question(object):

"""

Exercise parameters

"""
input_method = "MathKeyboard"
difficulty = 4
dirname = "../../../main/question_factory/int/generated_questions"


"""

Initialize the exercise

"""

def __init__(self, cur, new):
questionFileName = self.dirname + "/" + self.question_file()
self.questionNum = cur
with open(os.path.abspath(os.path.join(os.path.abspath(os.path.dirname(__file__)), questionFileName)), 'rb') as questionFile:
self.question = pickle.load(questionFile)

def question_file(self):
print self.questionNum <-
return "difficulty" + str(self.difficulty) + "_" + str(self.questionNum) + ".question"


and it is giving an error
'Question' object has no attribute 'questionNum'

on the marked line. Can you please help me with this? Thank you in advance.

Answer

The problem is that you call question_file in __init__ before you have initialized its variables. Set the variable first.

class Question(object):

    """

    Exercise parameters

    """
    input_method = "MathKeyboard"
    difficulty = 4
    dirname = "../../../main/question_factory/int/generated_questions"


    """

    Initialize the exercise

    """

    def __init__(self, cur, new):
        self.questionNum = cur
        questionFileName = self.dirname + "/" + self.question_file()
        with open(os.path.abspath(os.path.join(os.path.abspath(os.path.dirname(__file__)), questionFileName)), 'rb') as questionFile:
            self.question = pickle.load(questionFile)

    def question_file(self):
        print self.questionNum
        return "difficulty" + str(self.difficulty) + "_" + str(self.questionNum) + ".question"
Comments