TypeError: '>' 在 'method' 和 'int' 的实例之间不被支持

新手上路,请多包涵

我希望有人可以帮助解决这个问题。

我创建了一个类,其中包含一个函数,用于计算 4 个汽车列表中的汽车总数。

在另一个脚本上,我正在创建界面并想说如果“totalCars”的答案大于零,然后继续提供一种汽车。

但是,当我这样做时,出现此错误: TypeError: '>' not supported between instances of 'method' and 'int' 。这是代码:

 def totalCars(self):
    p = len(self.getPetrolCars())
    e = len(self.getElectricCars())
    d = len(self.getDieselCars())
    h = len(self.getHybridCars())
    totalCars = int(p) + int(e) + int(d) + int(h)
    return totalCars

在界面脚本上有:

 while self.totalCars > 0:

为了解决这个问题,我尝试使用布尔值,如下所示:

 def totalCars(self):
    p = len(self.getPetrolCars())
    e = len(self.getElectricCars())
    d = len(self.getDieselCars())
    h = len(self.getHybridCars())
    totalCars = int(p) + int(e) + int(d) + int(h)
    if totalCars > 0:
        return True

在我的应用程序脚本上:

  while self.totalCars is True

但这完全使程序崩溃并且根本无法运行。

欢迎任何指导。非常感谢。

原文由 Annelli 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.1k
1 个回答

这是因为 self.totalCars 是一个方法,您需要通过在末尾添加一对括号来 调用 它以获取它的返回值,如下所示:

 while self.totalCars() > 0:
     #Insert the rest here

否则,就像消息所说的那样,您正在将方法与数字进行比较,这是行不通的。

无需添加布尔值,但如果您坚持使用布尔值,则可以执行以下操作:

 while self.totalCars():    #Will run if self.totalCars() RETURNS True

同样,这在您的原始代码中并没有真正起作用,因为您忘记了括号。

希望这可以帮助。

原文由 SSBakh 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题