[英]problem with implenting __len__ with sqlalchemy func.count getting some kind of recursion error
代码 - 应该使用以下代码实现len magic方法:
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
我应该强调,只有在调用repr类方法时我才会收到此错误,但是当我调用len(q)时(q是我正在使用的类实例)我得到了正确的答案!
任何线索?
您正在尝试format
实例方法self.__len__
,而不是该实例方法返回的长度。
当您尝试format(self.__len__)
,它会调用self
引用的实例上的repr
,从而创建递归。
你需要在self.__len__()
(或len(self)
或self.len
)上使用format
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.