gpt4 book ai didi

python - __iter__ 中的类型错误

转载 作者:太空宇宙 更新时间:2023-11-04 01:35:26 24 4
gpt4 key购买 nike

def __init__(self, maximum, start=0, step=1):
"""Sets the maximum, start, and step"""
try:
self.maximum = math.ceil(maximum)
self.start = math.ceil(start)
self.step = math.ceil(step)
except TypeError:
return "Error, attributes must be of type int or float"
def __iter__(self):
"""Iterates over the range"""
return iter(range(self.start, self.maximum, self.step))

是相关代码。每当我打电话时,请说:

j = crange.ChangeableRange(4)
list(j)

我得到错误:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "crange.py", line 16, in __iter__
return iter(range(self.start, self.maximum, self.step))
TypeError: 'str' object cannot be interpreted as an integer

为什么?我该如何解决这个问题?

最佳答案

range 函数需要整数作为参数。看起来您已经为 startmaximumstep 创建了一个字符串,其中包含类似 self.maximum = int( math.ceil(最大值)).

另请注意,在 Python 2 中,math.ceil 函数返回一个浮点值,因此需要将其转换为整数。

在 Python 3 中,您的代码工作正常:

>>> import math
>>> class ChangeableRange:
def __init__(self, maximum, start=0, step=1):
"""Sets the maximum, start, and step"""
try:
self.maximum = math.ceil(maximum)
self.start = math.ceil(start)
self.step = math.ceil(step)
except TypeError:
return "Error, attributes must be of type int or float"
def __iter__(self):
"""Iterates over the range"""
return iter(range(self.start, self.maximum, self.step))


>>> j = ChangeableRange(4)
>>> print(list(j))
[0, 1, 2, 3]

关于python - __iter__ 中的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10368996/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com