python中的is, ==與對象的相等判斷


  在java中,對於兩個對象啊a,b,若a==b表示,a和b不僅值相等,而且指向同一內存位置,若僅僅比較值相等,應該用equals。而在python中對應上述兩者的是‘is’ 和‘==’。

(1) python中的基本類型的is判斷

  需要注意的是,對於python中的基本類型,如str,數值類型(int,long,float,complex)不要用is來做相等判斷,下面給出is判斷為False的例子:

str_123 = '123'
print 'id("123"):{}'.format(id(str_123))
itostr_123 = str(123)
print 'id(str(123)):{}'.format(id(itostr_123))

p1 = 256 + 1
p2 = 257
print 'id(p1):{}'.format(id(p1))
print 'id(p2):{}'.format(id(p2))

其結果是:

id("123"):40187864
id(str(123)):40121608
id(p1):40214096
id(p2):40214744

str或者是int變量的id並不相同。

(2) python中對象的相等判斷

  簡單的對於對象的相等判斷方式有兩種:

例如,自定義類Person:

class GenderEnum(object):
    MALE = 'MALE'
    FEMALE = 'FEMALE'


class Person(object):
    def __init__(self, name, gender=GenderEnum.MALE, age=0):
        self.name = name
        self.gender = gender
        self.age = age

    def __repr__(self):
        type('str')
        return '<Person %r %r %r>' % (self.name, self.gender, self.age)

若用==做如下判斷:

p1 = Person('tom', age=3)
p2 = Person('tom', age=3)
p3 = Person('jerry', age=5)
print 'id(p1):{}'.format(id(p1))
print 'id(p2):{}'.format(id(p2))
print 'id(p3):{}'.format(id(p3))
print p1 == p2
print p1 == p3

結果:

id(p1):39445784
id(p2):39445840
id(p3):39445896
False
False

p1,與p2的值雖然相同,但是地址不同。

想要判斷值相等,第一個方法是直接用instance.__dict__來判斷:

p1.__dict__ == p2.__dict__

另外一種方法是在Person class中加上自定義的__eq__函數:

    def __eq__(self, other):
        if self.name != other.name:
            return False
        if self.gender != other.gender:
            return False
        if self.age != other.age:
            return False
        return True

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM