问题implenting __len__与SQLAlchemy的func.count得到某种递归错误
问题描述:
代码 - 应该implent的len个魔术方法用下面的代码:问题implenting __len__与SQLAlchemy的func.count得到某种递归错误
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
我得到什么(3条上线保持在一个长长的清单重复,然后用下面的行终止):
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
我要强调调用再版类的方法,但是当时候我只收到此错误我叫len(q)(q是我正在使用的类实例)我得到正确答案!
任何线索?
答
您正在尝试format
实例方法self.__len__
,而不是该实例方法返回的长度。
当您尝试format(self.__len__)
时,它会调用repr
对self
所指的实例创建递归。
您需要在self.__len__()
(或len(self)
或self.len
)上使用format
。
你们刚才弄明白应该使用.len。不管怎么说,还是要谢谢你 – alonisser