【问题标题】:TypeError: '>' not supported between instances of 'method' and 'int'TypeError:“方法”和“int”的实例之间不支持“>”
【发布时间】:2018-10-20 13:02:40
【问题描述】:

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

我创建了一个类,其中包含一个函数,用于计算 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

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

欢迎在这里提供任何指导。 非常感谢。

【问题讨论】:

  • 请格式化您的代码。
  • @SimonH 我编辑了帖子,因为缩进在那里,在破坏格式的代码块之前只缺少空行。 Annelli:当您提出/编辑您的问题时,请使用预览功能,以确保它看起来像预期的那样。
  • 它是self.totalCars(),带括号。您没有调用该方法。
  • len() 返回一个整数,不需要 int 强制转换。
  • 谢谢安德拉斯,我回去编辑,看到有人已经有了。第一次发帖。非常感谢!

标签: python comparison-operators


【解决方案1】:

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

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

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

不需要添加布尔值,但如果你坚持使用一个,你可以这样做:

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

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

希望这会有所帮助。

【讨论】:

  • @MatthieuBrucher 废话,我的意思是“原始”totalCars()。我应该澄清这一点。谢谢。
【解决方案2】:

对于你的最后一个问题,你只需要这个:

while self.totalCars():

调用该方法,但不要检查True是否返回布尔值。

还有

def totalCars(self):

应该以:

结尾
return False

下次你还应该指出错误的确切位置。

【讨论】:

    【解决方案3】:

    不调用方法,不返回数据,无法与数字进行比较。

    您只需添加"()"

    while self.totalCars > 0:
    => while self.totalCars() > 0:
    

    【讨论】:

      【解决方案4】:

      当你使用count时也是如此,

      我在使用count时遇到了这个问题

      Model1.objects.filter(user=self.user).count > 1
      

      count 之后添加括号将使其工作?

      Model1.objects.filter(user=self.user).count() > 1
      

      【讨论】:

        猜你喜欢
        • 2020-09-07
        • 2018-09-03
        • 2020-11-13
        • 2021-01-15
        • 2020-06-02
        • 2019-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多