zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    _DataStructure_C_Impl:稀疏矩阵十字链表存储
    _DataStructure_C_Impl:稀疏矩阵三元组
    _DataStructure_C_Impl:Array
    _DataStructure_C_Impl:KMP模式匹配
    _DataStructure_C_Impl:链串
    _DataStructure_C_Impl:堆串
    _DataStructure_C_Impl:顺序串
    _DataStructure_C_Impl:双端队列
    _DataStructure_C_Impl:链式队列
    _DataStructure_C_Impl:只有队尾指针的链式循环队列
  • 原文地址:https://www.cnblogs.com/tlz888/p/6993799.html
Copyright © 2011-2022 走看看