0

私はこの奇妙なバグを抱えています

私はこのコードスニペットを持っています:

for prev_cand in self.candidates: #loop over a list of dicts
  if prev_cand == cand:
    print "I think these are equal!"
    print prev_cand, cand                                                   
    print "and here are their IDs!"                                         
    print id(prev_cand), id(cand)                                           
    print "and here are their string equalities!"                           
    print str(prev_cand) == str(cand)

これにより、次の結果が得られました。

I think these are equal!
{'H__0': 2} {'H__0': 1}
and here are their IDs!
27990448 27954960
and here are their string equalities!
False

何が起こっている?私は現在、文字列の等価性を使用するだけの回避策を使用していますが、それは正しい方法ではありません

私は彼らの情報にいくつかのプリントを追加しました:

and keys
['H__0'] ['H__0']
and type of keys
[<type 'str'>] [<type 'str'>]
and values
[2] [1]
and type of values
[<type 'instance'>] [<type 'instance'>]

小さな再現可能なコードを作成しようとしていますが、これまでのところできません。それでも頑張ります。私はpython 2.7.3を実行しています

さて、問題は 2 と 1 が int ではなく何らかの形で「インスタンス」型になっていることだと思います。
コメントありがとうございます!

4

1 に答える 1

0

1 と 2 を出力するクラスのインスタンス (repr のため) は同じインスタンスであるため、等しいです。基本的に、次のようなものがあります。

class Test:
count = 0
def __init__(self):
    self.a = ["1","2"]
def __repr__(self):
    b = self.a[self.__class__.count]
    self.__class__.count += 1
    return b

>>> a = Test()
>>> b = a
>>> a == b
True
>>> print a, b
1 2
于 2013-07-14T20:55:59.763 に答える