Iterable Derived class from file class in Python 2.6

Iterable Derived class from file class in Python 2.6

我有解决方法,但我仍在考虑实现目标的更好方法。我想要一个从 base class file 派生的 class 来逐行访问文件,但顺便获取行号。类似于 built-in enumerate 功能。

我觉得class应该是这样的:

class file2(file):
  def __init__(self, filename):
    file.__init__(self, filename)
    self._num_line = 0

  def __iter__(self):
    self._num_line = 0
    ?

实现这个

f2 = file2('myfile.txt')
for num_line, line in f2:
  ...

我目前的选择是在 child class:

中创建一个生成器
    def lines(self):
        for line in self:
            self._num_line += 1
            yield (self._num_line, line)

但用法很丑陋(好吧,不像我希望的那样 pythonic):

f2 = file2('myfile.txt')
gen = f2.lines()
for i, lin in gen:
   ...

有没有简单的方法可以做到这一点?提前致谢,

您的 __iter__ 方法可以与 def lines(self):

具有完全相同的实现

或者你可以这样做:

def __iter__(self):
    return enumerate(file.__iter__(self))

或者

def __iter__(self):
    return enumerate(super(file, self).__iter__())

请注意,我不应该鼓励这样做,因为它违反了 Liskov 替换原则。您的 iter 方法现在 returns 是元组的迭代器,而不是字符串的迭代器。只需在对象本身上使用 enumerate。为什么要使用继承?