2
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

为什么?我该如何解决?

4

1 回答 1

3

range函数需要整数作为参数。看起来您已经为startmaximumstep创建了一个字符串,例如self.maximum = int(math.ceil(maximum)).

另请注意,在 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]
于 2012-04-29T01:34:58.383 回答