Skip to main content
 首页 » 编程设计

python之了解 python 2.7 email.feedparser Feedparser __init__ 函数

2025年05月04日19wayfarer

(所以我正在尝试学习 python。我认为阅读比我更好的人的代码会很好。我决定通读电子邮件模块...)

email.feedparser 模块中 Feedparser 类的 init 函数定义为:

def __init__(self, _factory=message.Message): 
    """_factory is called with no arguments to create a new message obj""" 
    self._factory = _factory 
    self._input = BufferedSubFile() 
    self._msgstack = [] 
    self._parse = self._parsegen().next 
    self._cur = None 
    self._last = None 
    self._headersonly = False 

我遇到的问题是:

self._parse = self._parsegen().next 

我认为这应该意味着“将属性 self._parse 设置为方法 self._parsegen( )

据我所知,self._parsgen() 在 __init__() 期间调用时将首先调用 self._new_message()这将为 self._cur、self._last 和 self._msgstack 设置/添加值。然后它将一个空列表对象分配给局部变量 headers 然后开始遍历 self._input 对象。我认为 line 的第一个值将是一个 NeedMoreData 对象。因为 NeedMoreData 类只是扩展对象,所以它不应该有名为 next 的属性或方法。那么 next 是否只是返回迭代器 (self._input)?

有什么方法可以在解释器中查看它,以便我可以单步执行脚本的每一行?

请您参考如下方法:

So does next just refer back to the iterator (self._input)?

next 确实引用了生成器。由于 _parsegen() 方法使用了 yield,它返回一个生成器对象。考虑以下简单示例(来自 IPython):

In [1]: def a(): 
   ...:     yield 1 
   ...:     yield 2 
   ...:      
 
In [2]: a() 
Out[2]: <generator object a at 0x1a56550> 
 
In [3]: a().next 
Out[3]: <method-wrapper 'next' of generator object at 0x1a567d0> 
 
In [4]: a().next() 
Out[4]: 1 

所以,是的,您基本上是对的。它将下降到迭代器,并引用从中返回下一个值的方法。

Is there any way to have a look at this in the interpreter so that I can step through each line of the script?

您可以使用 pdb为了那个原因。