Python:httplib中令人费解的行为

2024-04-19 05:46:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我在httplib中添加了一行(import pdb; pdb.set_trace())HTTPConnection.putheader,这样我就能看到里面发生了什么。在

Python26\Lib\httplib.py,第489行:

def putheader(self, header, value):
    """Send a request header line to the server.

    For example: h.putheader('Accept', 'text/html')
    """
    import pdb; pdb.set_trace()
    if self.__state != _CS_REQ_STARTED:
        raise CannotSendHeader()

    str = '%s: %s' % (header, value)
    self._output(str)

然后从翻译那里查到这个

^{pr2}$

。。。正如预期的那样,PDB开始发挥作用:

> c:\python26\lib\httplib.py(858)putheader()
-> if self.__state != _CS_REQ_STARTED:
(Pdb)

在PDB中,我可以动态地计算表达式,所以我尝试输入self.__state

(Pdb) self.__state
*** AttributeError: HTTPConnection instance has no attribute '__state'

这是个例子。但是,当我输入step时,调试器将通过

if self.__state != _CS_REQ_STARTED:

线路没有问题。为什么会这样?如果self.__state不存在,python将不得不像我输入表达式时那样引发一个异常。在

Python版本:win32上的2.6.4


Tags: pyimportselfiftracecsreqhttplib
2条回答

回答我自己的问题:

http://en.wikipedia.org/wiki/Name_mangling#Name_mangling_in_Python

__state是对象内部的一个私有名称,它被改为_HTTPConnection__state,因此当我想在PDB中访问它时,我必须将其命名为self._HTTPConnection__state。只有对象可以将其称为__state。在

If the self.__state doesn't exist python would have to raise an exception as it did when I entered the expression.

在Python中,不必显式声明变量。 当你分配给他们时,他们就“出生”了。在

一些像pylint这样的代码验证器会对这些情况发出警告。 在您的例子中,您可以在HTTPConnection.__init__()中使用self.__state = None

但这不是很重要。在

相关问题 更多 >