【问题标题】:Why does it give the " 'int' object is not callable" with my custom class [duplicate]为什么我的自定义类会给出“'int'对象不可调用”[重复]
【发布时间】:2020-09-26 08:30:42
【问题描述】:

我正在 python 中制作这个非常简单的遗传算法。我制作了一个自定义类,它将成为不断发展的“生物”。我创建了该类的实例,当我尝试从其中一个对象调用该类的函数时,它给了我“'int' object is not callable”错误。

这是我所有的代码:

import random as random

class Creature:
    def __init__(self, value1, value2, value3, generation, index):
        self.value1 = value1
        self.value2 = value2
        self.value3 = value3
        self.generation = generation
        self.index = index

    def generation(self):
        test = self.value1 * self.value2 - self.value3
        if test >= 50:
            newGeneration.append(self)
            self.index = len(newGeneration)


creatures = []
newGeneration = []
for i in range(100):
    value1 = random.randint(5,10)
    value2 = random.randint(5,30)
    value3 = random.randint(30,50)
    creatures.append(Creature(value1, value2, value3, 1, i))


for i in range(len(creatures) - 1):
    creatures[i].generation()


for i in newGeneration:
    print(i.value1 * i.value2 - i.value3)

运行时,它给了我这个:

    line 29, in <module>
    creatures[i].generation()
TypeError: 'int' object is not callable

提前谢谢你

【问题讨论】:

  • generation 属性是一个int 你不能调用它
  • 你有self.generation 作为属性和方法。更改其中之一。

标签: python function class error-handling compiler-errors


【解决方案1】:

您尝试调用方法generation,但它被generation 属性隐藏,而generation 是一个int。

我会调用方法generate

class Creature:
    def __init__(self, value1, value2, value3, generation, index):
        self.value1 = value1
        self.value2 = value2
        self.value3 = value3
        self.generation = generation
        self.index = index

    def generate(self):
        test = self.value1 * self.value2 - self.value3
        if test >= 50:
            newGeneration.append(self)
            self.index = len(newGeneration)

【讨论】:

    【解决方案2】:

    尝试取出-1,范围函数已经将第一个数字向下取到0;所以它给了你错误,因为你试图打电话给creatures[-1],尽管我认为这必须工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-12
      • 2017-05-29
      • 1970-01-01
      • 2015-01-30
      • 1970-01-01
      • 2018-01-24
      相关资源
      最近更新 更多