Ruby Ruby - 4 months ago 15
Python Question

'module' object has no attribute 'questiоn'. Class name considered an attribute?

I'm trying to make a quiz for my project and I'm getting this error:

AttributeError: 'module' object has no attribute 'question'
. I don't understand why it thinks my class is an attribute.


  • questionbf.py is where I made the binary file.

  • quizbf.py is where I'm trying to make the quiz scoring right.



I'm lacking experience in Python so anything at all would be helpful. Thank you.

questionbf.py

import pickle
class question:
def __init__(self,a,b,c):
self.q=a
self.an=b
self.o=c

f1=open("Question.DAT","wb")
n=input("Enter no. of Questions ")
for i in range(n):
a=raw_input("Enter Question ")
b=raw_input("Enter Answer ")
c=raw_input("Enter Options ")
s=question(a,b,c)
pickle.dump(s,f1)
f1.close()


quizbf.py

import pickle

print '''Welcome to the revision quiz.'''

print
score=0
w=0
c=0
f1=open("Question.DAT","rb")
try:
while True:
s=pickle.load(f1)
print s.q
print s.o
guess=input("Enter Choice ")
if guess==s.a:
print "Correct!!"
print
score=score+1
c=c+1
elif guess=="exit" or guess=="Exit":
break
else:
w=w+1
print "Incorrect. Better luck next time!!"
print
except EOFError:
f1.close()
print s
print w


Error:

Traceback (most recent call last):
File "C:\Users\RUBY\Desktop\questionbf.py", line 32, in <module>
s=pickle.load(f1)
File "C:\Python27\lib\pickle.py", line 1378, in load
return Unpickler(file).load()
File "C:\Python27\lib\pickle.py", line 858, in load
dispatch[key](self)
File "C:\Python27\lib\pickle.py", line 1069, in load_inst
klass = self.find_class(module, name)
File "C:\Python27\lib\pickle.py", line 1126, in find_class
klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'question'

Answer

When you pickle an instance of a class the class name is saved in the pickle to allow the reading program to import the necessary module and gain access to the required class. Unfortunately the class whose elements you are pickling is in the __main__ module, which is the name Python gives to the module that is being executed.

Unfortunately, when your second program reads the pickle, it therefore looks for the question class in the __main__ module, which this time is the second program. So pickle complains that the given class (__main__) does not contain the required class (a defined class is an attrinute in its module just like a method of a class is an attribute in the class).

The necessary fix is to move the question class to a separate module, which your first program explicitly imports (using something like from new_module import question). Your second program will then know it needs to import new_module in order to access the question class, which it will do automatically (i.e. with no need to explicitly import it).

Comments