i有一个Case
类型的dict
对象列表,该对象使用dict
启动。在Python2中运行时,我可以循环浏览键和值,以促进我使用six
库的两个版本。
class Case:
def __init__(self, obj):
properties = {}
# standardize Boolean properties
true_values = ['1', 1, True, 'yes', 'Yes', 'YES']
false_values = ['0', 0, False, 'no', 'No', 'NO']
for (k, v) in iteritems(properties):
# standardize TRUE values
if v in true_values:
properties[k] = True
# standardize FALSE values
elif v in false_values:
properties[k] = False
# keep String values
elif isinstance(v, str):
continue
# remove NULL values
filtered = {k: v for (k, v) in iteritems(properties) if v != None}
# set Case instance attribute for each property
for (k, v) in iteritems(filtered):
setattr(self, k, v)
def __iter__(self):
return self
def __getitem__(self, key):
return self.__dict__.get(key, None)
def to_json(self):
return json.dumps(self, default=lambda o: o.__dict__)
当我浏览此列表时,尽管遵循six
文档,但我还是会得到一个属性。
i通过上述对象的列表进行迭代:
from six import iteritems
def transform(case_list):
for case in case_list:
for (key, value) in iteritems(case): #crashes here
#do stuff
,但每次都会获取一个属性:
Traceback (most recent call last):
File "app/run.py", line 134, in <module>
main()
File "/home/user/other.py", line 55, in transform
for (key, value) in iteritems(case):
File "/home/user/env/lib/python3.4/site-packages/six-1.10.0-py3.4.egg/six.py", line 581, in iteritems
return iter(d.items(**kw))
AttributeError: 'Case' object has no attribute 'items'
我用python3 app/run.py
称呼它。为什么它不识别峰值?
我通过在案例类中添加items()
方法来找到解决方案:
def items(self):
return zip(self.__dict__.values(), self.__dict__.keys())