【问题标题】:Use of "self" in a python class在 python 类中使用“self”
【发布时间】: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)

标签: python concept


【解决方案1】:

原因是因为__iter__ 是当您尝试迭代自定义类实例时被调用的。 这就是为什么当你迭代你的类时它工作得很好,因为你的类是可迭代的,只要你实现了__iter__ 函数。

迭代返回连续计数,因为在每个 next 函数上,它实际上调用了您实现时的自定义 __next__ 函数 - 调用 self._advance() 之前 self._current (同样,在 __iter__ 上返回的变量)。

希望这个解释对你有意义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    • 2016-09-05
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    相关资源
    最近更新 更多