【发布时间】:2020-12-19 18:54:46
【问题描述】:
我正在处理从 python2 到 python3 的代码迁移。我对 Python 中的 OOP 和 OrderedDict 没有太多经验。这是我无法解决的问题。 before 也有人问过类似的问题,但似乎对这种情况没有任何作用。我有以下代码:
for row in rows:
new_ = dummy(row.attr, row.error_type, row.array_agg_1,
row.with_error, row.total, row.level, row.order_)
if new_ in result[n.id]: # <- never becomes true
print('I am in the if')
if new_.with_error is not None:
result[n.id][new_][1] += new_.with_error
result['total'][new_][1] += new_.with_error
else:
print('I am in the else')
if new_.with_error is not None:
result[n.id][new_] = [new_.attr, new_.with_error]
此代码在 python2 中有效。但是,python3 版本无法执行外部if 语句。
result[n.id] 是一个OrderedDict,看起来像这样:
#an example of result[n.id]
>>> ([(Eclipse Required Items'nce'[1540972], ['Eclipse Required Items', 1, 1, [1540972], 'nce', 1, 1681]),
(Other Story Tab Info learned/discovered documentation and accuracy'nce'[1540973], ['Other Story Tab Info learned/discovered documentation and accuracy', 1, 1, [1540973], 'nce', 1, 1684]),
(Other (please provide detail in Comments section)'bce'[1541001], ['Other (please provide detail in Comments section', 1, 1, [1540973], 'bce', 1, 1684]
(Other Static bar information was documented'nce'[1540974], ['Other Static bar information was documented', 1, 1, [1541001], 'nce', 1, 1707])])
#type of result[n.id]
>>> <class 'collections.OrderedDict'>
new_ 看起来像这样:
#print(new_)
Other (please provide detail in Comments section)'bce'[1541001]
#print(type(new_))
<class 'smd.lib.asynch.calibration.dummy'>
我尝试过的事情
if str(new_) in str(result[n.id]):
它可以在内部使用 KeyError 失败,我不确定这是否是最好的方法。此外,它可能会破坏软件的其他功能。
if new_ in result[n.id].keys():
不起作用。任何解决问题的帮助和指导将不胜感激。
dummy 类如下所示:
class dummy(object):
def __init__(self, attr, error_type, path, with_error=None, total=None,
level=None, order=None):
self.attr = attr
self.error_type = error_type
self.path = path
self.with_error = with_error
self.total = total
self.level = level
self.order = order
def __cmp__(self, other):
return not (
self.attr == other.attr and self.error_type == other.error_type
and self.path == other.path
)
def __base_repr__(self):
return "{0}{1}{2}".format(self.attr, self.error_type, self.path)
def __hash__(self):
return hash(self.__base_repr__())
def __repr__(self):
return self.__base_repr__()
【问题讨论】:
-
删除
__cmp__,改为实现__eq__。 -
@balderman 感谢您的洞察力。我会调查一下。你能推荐一个很好的资源来学习吗? this 是个好资源吗?
-
@balderman 感谢您的帮助。现在可以了。你介意写一个答案吗?我很乐意接受并结束这个问题。
-
很高兴为您提供帮助。写了一个答案。
标签: python python-3.x dictionary python-2to3