【发布时间】:2021-01-06 00:56:08
【问题描述】:
我正在学习 python 中的类并做一个小练习。在这里,我创建了一个“Progression”类,并遇到了 print_progression 方法的问题。我了解我得到的 TypeError 但不了解解决方案。解决方案是将 self 传递给下一个方法。所以基于解决方案,我是否应该推断出 self 的类型是“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, 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
TypeError: 'int' object is not an iterator
我发现 self._current 是一个 int 类型,不应该传递给 next 方法。相反,我应该将 self 传递给下一个方法,它可以正常工作。
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)) for i in range(0,values_to_print)))
【问题讨论】:
-
将
str(next(self._current)更改为str(self._current+1)