如何获取没有 __dict__ 的 Python 对象的属性列表?
对于 xml.etree 的实例,您将如何执行此操作.cElementTree.Element
?
$ python
Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
>>> from xml.etree.cElementTree import Element
>>> obj = Element('aaa')
>>> obj
<Element 'aaa' at 0x101bde270>
>>> dir(obj)
['__copy__', '__deepcopy__', '__reduce__', 'append', 'clear', 'extend', 'find', 'findall', 'findtext', 'get', 'getchildren', 'getiterator', 'insert', 'items', 'iter', 'iterfind', 'itertext', 'keys', 'makeelement', 'remove', 'set']
>>> obj.tag
'aaa'
How would you do this for an instance of xml.etree.cElementTree.Element
?
$ python
Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
>>> from xml.etree.cElementTree import Element
>>> obj = Element('aaa')
>>> obj
<Element 'aaa' at 0x101bde270>
>>> dir(obj)
['__copy__', '__deepcopy__', '__reduce__', 'append', 'clear', 'extend', 'find', 'findall', 'findtext', 'get', 'getchildren', 'getiterator', 'insert', 'items', 'iter', 'iterfind', 'itertext', 'keys', 'makeelement', 'remove', 'set']
>>> obj.tag
'aaa'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果通过自定义
__getattr__
或__getattribute__
返回属性,则不尝试就无法知道是否会返回属性,并且在不尝试所有可能的名称的情况下无法获得完整列表。您可以通过dir()
。If attributes are returned via custom
__getattr__
or__getattribute__
, you cannot know whether an attribute will be returned without trying and you cannot get a full list without trying all possible names. You can get the list of static attributes viadir()
.xml.etree.ElementTree.Element
对象确实有一个__dict__
。__dict__
是当前定义的属性的字典。dir()
调用__dir__()
,它可能会被覆盖。The
xml.etree.ElementTree.Element
object does have a__dict__
.The
__dict__
is the dictionary of currently defined attributes.dir()
calls__dir__()
, which may be overrided.