简体   繁体   English

使用sqlalchemy func.count实现__len__会出现某种递归错误的问题

[英]problem with implenting __len__ with sqlalchemy func.count getting some kind of recursion error

the code - supposed to implent the len magic method with the following code: 代码 - 应该使用以下代码实现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

what I get (the 3 upper lines keep on repeating in a long list and then terminate with the following line): 我得到了(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

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! 我应该强调,只有在调用repr类方法时我才会收到此错误,但是当我调用len(q)时(q是我正在使用的类实例)我得到了正确的答案!

any clues? 任何线索?

You're trying to format an instance method, self.__len__ , not the length returned by that instance method. 您正在尝试format实例方法self.__len__ ,而不是该实例方法返回的长度。

When you try to format(self.__len__) , it calls repr on the instance referred to by self , creating the recursion. 当您尝试format(self.__len__) ,它会调用self引用的实例上的repr ,从而创建递归。

You need to use format on self.__len__() (or len(self) or self.len ). 你需要在self.__len__() (或len(self)self.len )上使用format

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM