python is id == 的差别,cmp方法
2012-12-04 18:50
344 查看
1. id():获取的是对象在内存中的地址
2. is :比对2个变量的对象引用(对象在内存中的地址,即id() 获得的值)是否相同。如果相同则返回True,否则返回False。换句话说,就是比对2个变量的对象引用是否指向同一个对象。
3. ==:比对2个变量指向的对象的内容是否相同。
下面通过cmp函数比较两个对象的差异:
先看cmp函数的用法,原型为cmp(x, y),作用是比较两个对象x,y,如果x大于y返回正数,相等则返回0,否则返回负数,示例里MyClass类用了__cmp__,用以自定义比较对象,如果注释此方法,个人认为默认为会比较a,b对象的id值。
2. is :比对2个变量的对象引用(对象在内存中的地址,即id() 获得的值)是否相同。如果相同则返回True,否则返回False。换句话说,就是比对2个变量的对象引用是否指向同一个对象。
3. ==:比对2个变量指向的对象的内容是否相同。
下面通过cmp函数比较两个对象的差异:
1 class MyClass(object): 2 def __init__(self, name): 3 self.name = name 4 5 def __cmp__(self, other): 6 return cmp(self.name, other.name) 7 8 9 10 a = MyClass('leon') 11 b = MyClass('leon') 12 print a is b 13 print a == b 14 print id(a) 15 print id(b) 16 print cmp(a, b)
先看cmp函数的用法,原型为cmp(x, y),作用是比较两个对象x,y,如果x大于y返回正数,相等则返回0,否则返回负数,示例里MyClass类用了__cmp__,用以自定义比较对象,如果注释此方法,个人认为默认为会比较a,b对象的id值。
相关文章推荐
- Python中NameError: name 'reload' is not defined 解决方法
- python中的is、==和cmp()比较字符串
- 关于id cannot be resolved or is not a field 的一个解决方法
- Python安装Imaging报错:The _imaging C module is not installed问题解决方法
- python中字典的比较方法——cmp
- python根据时间生成mongodb的ObjectId的方法
- python插入记录后取得主键id的方法
- python中sort()方法自定义cmp PythonTip-最大正整数
- 用CONNECT方法突破HTTP代理服务器的扩展名封锁(python) [转] - MyNewID - 博客园
- Python使用pip安装报错:is not a supported wheel on this platform的解决方法
- python的ID方法
- An App ID with identifier "xxxx.xxx.xxx" is not avalible 解决方法
- selenium +Python 测试时报 “Element is not visible”解决方法
- python中字符串比较使用is、==和cmp()总结
- Python中用eval将字符串转换为字典时候出错:NameError: name ‘null’ is not defined的解决方法
- Python安装Imaging报错:The _imaging C module is not installed问题解决方法
- An App ID with Identifier "xxx" is not available . Please enter a different string.解决方法
- python3开发进阶-Django框架中form的查看校验方法is_valid()的源码,自定义验证方法
- python操作mongodb根据_id查询数据的实现方法