__iter__中的TypeError

时间:2012-04-29 01:32:03

标签: python

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

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

1 个答案:

答案 0 :(得分:3)

range 函数需要参数的整数。您似乎已为{em> start , maximum step 创建了一个字符串,其中包含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]