SORU
4 AĞUSTOS 2009, Salı


Python öznitelikleri tarafından eşitlik için nesne örneklerini karşılaştırmak

Python eşitlik için bazı nesne iki örneği karşılaştırmak için en iyi yolu nedir? Gibi bir şey yapmak mümkün olmak istiyorum

Örnek:

doc1 = ErrorDocument(path='/folder',title='Page')
doc2 = ErrorDocument(path='/folder',title='Page')

if doc1 == doc2: # this should be True
    #do something

DÜZENLEME:

Daha fazla soru açıklığa kavuşturmak için. Öznitelik değerleri ile karşılaştırmak için, ve daha genel bir çözüm yapmak istiyorum

def __eq__(self, other):
    return self.path == other.path and self.title == other.title

__eq__() yöntem, bu gibi görünmelidir?

def __eq__(self, other):
    # Is the other instance of the same object
    # Loop through __dict__ and compare values to attributes of other

CEVAP
4 AĞUSTOS 2009, Salı


Her zamanki gibi Python ile kiss :

class Test(object):

    def __init__(self, attr1, attr2):
        self.attr1 = attr1
        self.attr2 = attr2

    def __str__(self):
        return str(self.__dict__)

    def __eq__(self, other): 
        return self.__dict__ == other.__dict__

t1 = Test("foo", 42)
t2 = Test("foo", 42)
t3 = Test("bar", 42)

print t1, t2, t3
print t1 == t2
print t2 == t3

Çıktılar:

{'attr2': 42, 'attr1': 'foo'} {'attr2': 42, 'attr1': 'foo'} {'attr2': 42, 'attr1': 'bar'}
True
False

N. B : önce Python 3.0, sana __eq__ aynı şekilde çalışmak yerine __cmp__ kullanmak için daha muhtemel olduğunu unutmayın.

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • julioissk84life

    julioissk84l

    18 ŞUBAT 2008
  • Kayla Caton - Peet

    Kayla Caton

    23 HAZİRAN 2012
  • pucksz

    pucksz

    24 Mart 2006