在Ubuntu 14.04lts版本的python2.7和python3.4上,__dict__属性按预期工作。_asdict方法也可以工作,但是我倾向于使用标准定义的、统一的属性api,而不是本地化的非统一api。
$python2.7美元# Works on:
# Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2
# Python 3.4.3 (default, Oct 14 2015, 20:28:29) [GCC 4.8.4] on linux
import collections
Color = collections.namedtuple('Color', ['r', 'g', 'b'])
red = Color(r=256, g=0, b=0)
# Access the namedtuple as a dict
print(red.__dict__['r']) # 256
# Drop the namedtuple only keeping the dict
red = red.__dict__
print(red['r']) #256
看到asdict是获得表示soemthing的字典的语义方法(至少据我所知)。
如果能积累一个包含主要python版本和平台及其对__dict__的支持的表,那就太好了,目前我只有一个平台版本和两个python版本,如上面所述。| Platform | PyVer | __dict__ | _asdict |
| -------------------------- | --------- | -------- | ------- |
| Ubuntu 14.04 LTS | Python2.7 | yes | yes |
| Ubuntu 14.04 LTS | Python3.4 | yes | yes |
| CentOS Linux release 7.4.1708 | Python2.7 | no | yes |
| CentOS Linux release 7.4.1708 | Python3.4 | no | yes |
| CentOS Linux release 7.4.1708 | Python3.6 | no | yes |