我有一个在Python2中传递但在Python3中失败的测试,我试图找出原因.测试在以下行失败:
self._timeseries[0].resource.__dict__
Run Code Online (Sandbox Code Playgroud)
有错误:
AttributeError: 'Resource' object has no attribute '__dict__'
Run Code Online (Sandbox Code Playgroud)
如果我调试测试,并在调试器中打印对象,我可以看到以下内容:
(Pdb) p self._timeseries[0].resource.__dict__
OrderedDict([('type', 'type_value'), ('labels', {'label1': 'value1', 'label2': 'value2', 'label3': 'value3'})])
Run Code Online (Sandbox Code Playgroud)
如果我在Python3调试器中执行相同操作,我会得到:
(Pdb) p self._timeseries[0].resource.__dict__
*** AttributeError: 'Resource' object has no attribute '__dict__'
Run Code Online (Sandbox Code Playgroud)
任何想法为什么会这样?如果我在没有调试器的情况下将它打印出来,那么该对象看起来完全一样.__dict__,为什么Python3会失败呢?
yel*_*yed 14
所以我在经过一些挖掘后找到了答案,这确实是Python2和Python3之间的差异,这是一个非常重要的.
事实证明,Resource代码中的类型实际上是一个命名元组.在Python2中,.__dict__添加为方便的属性包装器._asdict(),但这不是在Python3中完成的:
https://docs.python.org/2/library/collections.html#collections.somenamedtuple._asdict(在__dict__此处查找)
https://docs.python.org/3/library/collections.html#collections.somenamedtuple._asdict
所以它看起来._asdict实际上是事实的来源,应该用于便携式2to3代码.
值得一提的是,vars它也是仅存在于Python2中的包装器.
| 归档时间: |
|
| 查看次数: |
10951 次 |
| 最近记录: |