问题描述
我正在学习python中的类并做一些小练习。在这里,我创建了一个“ Progression”类,并且print_progression方法有问题。我了解我得到的TypeError,但不了解解决方案。解决的办法是将自身传递给下一个方法。因此,根据解决方案,我应该推断出自己的类型为“ iter”。
class Progression:
""" Iterator producing a generic progression.
Default progresssion : 0,1,2 """
def __init__(self,start=0):
self._current = start
def _advance(self):
""" This should be overridden by a subclass to customize progression """
self._current += 1
return self._current
def __next__(self):
if self._current == None:
raise stopiteration()
else:
return self._advance()
def __iter__(self):
return self._current
def print_progression(self,values_to_print):
if self._current != None:
print(type(self))
# print(isinstance(self,iter)) # TypeError: isinstance() arg 2 must be a type or tuple of types
print(" ".join(str(next(self._current)) for i in range(0,values_to_print)))
创建类的实例
p = Progression(start=1)
p.print_progression(3)
<class '__main__.Progression'>
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-83-19a69bdc9721> in <module>()
1 p = Progression(start=1)
----> 2 p.print_progression(3)
1 frames
<ipython-input-81-f0653f30c8f0> in print_progression(self,values_to_print)
25 print(type(self))
26 # print(isinstance(self,iter)) # TypeError: isinstance() arg 2 must be a type or tuple of types
---> 27 print(" ".join(str(next(self._current)) for i in range(0,values_to_print)))
28
<ipython-input-81-f0653f30c8f0> in <genexpr>(.0)
25 print(type(self))
26 # print(isinstance(self,values_to_print)))
28
TypeError: 'int' object is not an iterator
我发现self._current是一个int类型,不应传递给下一个方法。相反,我应该将self传递给下一个方法,它可以正常工作。
class Progression:
""" Iterator producing a generic progression.
Default progresssion : 0,iter)) # TypeError: isinstance() arg 2 must be a type or tuple of types
print(" ".join(str(next(self)) for i in range(0,values_to_print)))
解决方法
原因是因为尝试迭代自定义类实例时会调用__iter__
。
这就是为什么当您遍历类时它可以正常工作的原因,因为只要实现了__iter__
函数,您的类就可以迭代。
迭代返回相应的计数,因为在每个next
函数上,它实际上都调用了您实现的自定义__next__
函数-调用self._advance()
之前的self._current
(再次,在__iter__
返回的变量。)
希望这种解释对您有意义。