the code – supposed to implent the len magic method with the following code:
def __len__(self):
from sqlalchemy import func
self.len = session.query(func.count(Question.id)).scalar()
return int(self.len)
def __repr__(self):
self.repr = "traffic theory question, current number of questions:{0}".format(self.__len__)
return self.repr
what I get (the 3 upper lines keep on repeating in a long list and then terminate with the following line):
File "C:\Python27\dir\file.py", line 129, in __repr__
self.repr = "traffic theory question, current number of questions:{0}".format(self.__len__)
RuntimeError: maximum recursion depth exceeded while getting the str of an object
I should stress I’m getting this error only when calling the repr class method but when I call len(q) (q is the class instance i’m working with) I get the right answer!
any clues?
You’re trying to
formatan instance method,self.__len__, not the length returned by that instance method.When you try to
format(self.__len__), it callsrepron the instance referred to byself, creating the recursion.You need to use
formatonself.__len__()(orlen(self)orself.len).