通常我通过使用vars()或object .__ dict __来获取对象属性的dict,但这对许多对象都不起作用:
使用ZipInfo对象时,我得到:
In [11]: f
Out[11]: <zipfile.ZipInfo at 0x7f4c27fa9e60>
In [12]: vars(f)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-14-b663d4bf75ea> in <module>()
----> 1 vars(f)
TypeError: vars() argument must have __dict__ attribute
我发现获得词典的唯一方法是:
In [18]: { k:getattr(f,k) for k in dir(f) if not k.startswith('_') }
Out[18]:
{'CRC': 1070265580,
'FileHeader': <bound method ZipInfo.FileHeader of <zipfile.ZipInfo object at 0x7f4c27fa9e60>>,
'comment': '',
'compress_size': 73088,
'compress_type': 8,
'create_system': 0,
'create_version': 20,
'date_time': (2017, 3, 9, 17, 11, 44),
'external_attr': 0,
'extra': '',
'extract_version': 20,
'file_size': 720193,
'filename': u'stateCaptureData.txt',
'flag_bits': 2056,
'header_offset': 0,
'internal_attr': 0,
'orig_filename': 'stateCaptureData.txt',
'reserved': 0,
'volume': 0}
有更正式的方法吗?