列出对象的所有属性

时间:2013-09-03 04:48:22

标签: python

我正在尝试导入并使用此处找到的名为“wikipedia”的模块...

https://github.com/goldsmith/Wikipedia

我可以使用dir函数检查所有属性。

>>> dir(wikipedia)
['BeautifulSoup', 'DisambiguationError', 'PageError', 'RedirectError', 'WikipediaPage', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'cache', 'donate', 'exceptions', 'page', 'random', 'requests', 'search', 'suggest', 'summary', 'util', 'wikipedia']

但是 wikipedia.page 不会返回它的所有子属性(!?)

>>> dir(wikipedia.page)
['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']

我希望在此列表中看到标题,内容等属性。我如何知道“页面”中隐藏的属性是什么?

2 个答案:

答案 0 :(得分:5)

因为wikipedia.page是一个函数。我想你想要的是WikipediaPage对象的属性。

>>> import wikipedia
>>> ny = wikipedia.page('New York')
>>> dir(ny)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'content', 'html', 'images', 'links', 'load', 'original_title', 'pageid', 'references', 'summary', 'title', 'url']

这两者的类型不同。

>>> type(ny)
<class 'wikipedia.wikipedia.WikipediaPage'>
>>> type(wikipedia.page)
<type 'function'>

答案 1 :(得分:0)

您可能还想查看__dict__这是一个不错的小故事

>>> class foo(object):
...     def __init__(self,thing):
...         self.thing= thing
...
>>> a = foo('pi')
>>> a.__dict__
{'thing': 'pi'}

或vars做同样的事情:

>>> vars(a)
{'thing': 'pi'}
相关问题