英文:
Why am I getting a TypeError the second time I run a class method?
问题
新手学习Python和编程,目前正在学习关于类和对象,感到很困惑。在这个特定的示例中,我有一个Animal父类和一个EggLayers子类。EggLayers类有一个方法来计算特定实例的每周产蛋量,然后将该值附加到列表中。我还有另一个方法来计算鸡的寿命产蛋量。思路是,每周的总数从运行第一个方法的列表中获取,然后第二个方法对列表进行求和以返回实例的寿命总产蛋量。第一次运行时两者都运行正常,但是,当我尝试第二次运行第一个方法时,出现TypeError('int'对象不可调用)。
我尝试了在代码中的各个位置使用int()。也不认为我在任何地方重写int()函数。显然,这是导致此错误的两个最常见原因。如果有上述任何一个问题,我不认为它会在第一次运行时正常运行。
class EggLayers(Animal):
"""A class for egg laying animals"""
type = "chicken"
def __init__(self, name, age, color, tag):
super().__init__(name, age, color, tag)
def eggs_week(self): # 计算每周产蛋数并附加到列表
self.eggs_list = []
self.eggs_day = int(input("Eggs today? "))
self.eggs_day = self.eggs_day
self.eggs_week = self.eggs_day * 7
self.eggs_list.append(self.eggs_week)
print(f"{self.name} laid {self.eggs_week} this week")
return self.eggs_week
def eggs_lifetime(self): # 对上述列表中的值进行求和
self.eggs_lifetime = sum(self.eggs_list)
print(f"Lifetime production for {self.name} is {self.eggs_lifetime}")
return self.eggs_lifetime
chicken1 = EggLayers('chicken1', 3, 'white', '002')
chicken1.eggs_week()
chicken1.eggs_lifetime()
chicken1.eggs_week() # 仅在第二次运行时出现错误
希望这可以帮助您解决问题。
英文:
New to Python and programming in general. Currently learning about classes and objects and really struggling. In this particular example, I have an Animal parent class and a EggLayers child class. The EggLayers class has a method to calculate a particular instance's egg production for the week and then append the value to a list. I have another method that calculates the chicken's lifetime production. The idea being, each week's totals go into a list from running the first method and then the second method sums the list to return a lifetime total for the instance. Both run fine the first time around, however, when I try to run the first method a second time I get a TypeError ('int' object is not callable).
I've tried int() in various places in the code. Also don't think I'm overriding the int() function anywhere. Apparently these are the two most common reasons for this error. Wouldn't think it would run the first time if I had either of the above issues.
class EggLayers(Animal):
"""A class for egg laying animals"""
type = "chicken"
def __init__(self, name, age, color, tag):
super().__init__(name, age, color, tag)
def eggs_week(self): # to calculate eggs/week and then append to list
self.eggs_list = []
self.eggs_day = int(input("Eggs today? "))
self.eggs_day = self.eggs_day
self.eggs_week = self.eggs_day * 7
self.eggs_list.append(self.eggs_week)
print(f"{self.name} laid {self.eggs_week} this week")
return self.eggs_week
def eggs_lifetime(self): # to sum the values in the list above
self.eggs_lifetime = sum(self.eggs_list)
print(f"Liftetime production for {self.name} is {self.eggs_lifetime}")
return self.eggs_lifetime
chicken1 = EggLayers('chicken1', 3, 'white', '002')
chicken1.eggs_week()
chicken1.eggs_lifetime()
chicken1.eggs_week() # Only throws an error the second time
答案1
得分: 3
因为在你的 eggs_week
函数中,你有以下代码:
self.eggs_week = self.eggs_day * 7
之后,chicken1.eggs_week
不再是一个函数,而是一个整数。
你实际上不需要在函数名前加前缀,因为它已经是一个与鸡蛋相关的类。此外,你计算的大多数值不需要保存为对象的状态,所以不需要使用 self.
。
更像这样的写法:
class EggLayers(Animal):
"""鸡蛋产量动物的类"""
type = "chicken"
def __init__(self, name, age, color, tag):
super().__init__(name, age, color, tag)
self.eggs_list = []
def per_week(self): # 计算每周的鸡蛋数量,然后添加到列表中
eggs_day = int(input("今天有多少鸡蛋? ")
eggs_week = eggs_day * 7
self.eggs_list.append(eggs_week)
print(f"{self.name}本周产了{eggs_week}个鸡蛋")
return eggs_week
def lifetime(self): # 计算以上列表中值的总和
eggs_lifetime = sum(self.eggs_list)
print(f"{self.name}的终身产量为{eggs_lifetime}个鸡蛋")
return eggs_lifetime
个人认为在类方法中进行输入/输出是不良的实践。类应该直接与对象相关的功能。它不应关心信息来自何处。例如,目前,你无法轻松使用它从文件或数据库中读取数据。
我会在类外部使用循环请求输入,然后有一个类方法允许我传递该信息,比如 add_week
。但是,我在这里没有进行这种更改。
英文:
It's because in your eggs_week
function, you have
self.eggs_week = self.eggs_day * 7
After that, chicken1.eggs_week
is no longer a function. It's an integer.
You don't really need to include a prefix on your function names, since it's already an eggs-related class. Also, most of the values you compute do not need to be saved as state in the object, so they do not need self.
.
More like this:
class EggLayers(Animal):
"""A class for egg laying animals"""
type = "chicken"
def __init__(self, name, age, color, tag):
super().__init__(name, age, color, tag)
self.eggs_list = []
def per_week(self): # to calculate eggs/week and then append to list
eggs_day = int(input("Eggs today? "))
eggs_week = eggs_day * 7
self.eggs_list.append(eggs_week)
print(f"{self.name} laid {eggs_week} this week")
return eggs_week
def lifetime(self): # to sum the values in the list above
eggs_lifetime = sum(self.eggs_list)
print(f"Liftetime production for {self.name} is {eggs_lifetime}")
return eggs_lifetime
Personally, I think it is bad practice to do I/O in a class method like this. The class should hold functionality directly related to the object. It should not care where the information comes from. For example, right now, you couldn't easily use this to read the data from a file or a database.
I would have a loop outside the class asking for the input, then have a class method that allows me to pass that information in, like add_week
. However, I haven't made that change here.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论