为什么 vars(response) 不显示 response.text? (使用 Python 请求模块)

Why does vars(response) not show response.text? (using Python Requests module)

import requests
response = requests.get('http://httpbin.org/get')
print vars(response) # no response.text listed
print response.text # value printed

为什么 vars(response) 不列出 response.text 当该值存在时?

dir(response) 会列出 response.text,但不会打印它的值。

它不在 vars 结果中,因为 vars 不会将属性解析为对象的父 class。参见 this other thread on SO

您可以通过在对象上使用 dir 来请求所有 "attributes, its class's attributes, and recursively the attributes of its class's base classes":

In [1]: import requests

In [2]: response = requests.get('http://httpbin.org/get')

In [3]: 'text' in vars(response)
Out[3]: False

In [4]: 'text' in dir(response)
Out[4]: True

对于第一个问题,text 没有出现在 vars 中的原因是 because it's a property(由 @property 定义)而不是 class 属性(vars 显示的 __dict__ 中的内容)。

对于第二个问题,这是因为dirvars的工作方式。

来自 vars 的文档:

vars([object])

Return the dict attribute for a module, class, instance, or any other object with a dict attribute.

Objects such as modules and instances have an updateable dict attribute; however, other objects may have write restrictions on their dict attributes (for example, new-style classes use a dictproxy to prevent direct dictionary updates).

Without an argument, vars() acts like locals(). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.

对于dir

The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:

If the object is a module object, the list contains the names of the module’s attributes. If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases. Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.

所以基本上dir只是打印出传入参数的属性,不是其对应的值。

此外,this answer 对差异的解释非常全面。