Python的is和==区别(整理)
来源:互联网 发布:矩阵的秩ppt 编辑:程序博客网 时间:2024/06/08 05:41
is和==的区别
解释1
==
is for value equality. Use it when you would like to know if two objects have the same value.is
is for reference equality. Use it when you would like to know if two references refer to the same object.
解释2
is
: if two variables point to the same object.==
: if the objects referred to by the variables are equal.
解释3
python中的每个对象都有三种属性:id
, value
, type
. 不同对象实例的id
一定是不同的,可以把id
看做是和内存地址一一对应的。而value
只是检查两个变量的内容是否相等。
解释4
==
会调用对应类里的__eq__()
函数。例如:
class Name(object): def __eq__(self, other): print('__eq__() is called.')name1 = Name()name2 = Name()print(name1 == name2)
结果:
__eq__() is called.None # __eq__()里面没有return,所以==的结果为None
然而如果没有重写__eq__()
函数,我猜测就会去调用is
的操作。例如:
class Name(object): pass# 创建两个不同的Name对象name1 = Name() name2 = Name()# 让name3和name1指向同一个Name对象name3 = name1print(name1 is name2, name1 == name2)print(name1 is name3, name1 == name3)
结果:
False FalseTrue True
例外情况:
This is inconsistent with the earlier result. It turns out the reference implementation of Python caches integer objects in the range -5~256 as singleton instances for performance reasons.
Example:
for i in range(1, 10): a = -i is_res = a is int(str(a)) print("%i: %s" % (a, is_res))print()for i in range(250, 260): a = i is_res = a is int(str(a)) print("%i: %s" % (a, is_res))
results:
-1: True-2: True-3: True-4: True-5: True-6: False-7: False-8: False-9: False250: True251: True252: True253: True254: True255: True256: True257: False258: False259: False
参考:Is there a difference between ==
and is
in Python?
阅读全文
0 0
- Python的is和==区别(整理)
- python is 和==的区别
- Python中is和==的区别和联系
- Python中is和==的区别
- Python中is和==的区别
- python中 is 和 == 的区别
- 在python 中is和= = 的区别
- 在python 中is和= = 的区别
- python中is和 == 的区别
- Python中is和==的区别
- [基础] - Python中 is 和 == 的区别
- Python判断语句中‘is’和‘==’的区别
- Python中is和==的区别
- Python中==和is的区别
- python中is和==的区别
- Python自学之is和‘==’的区别
- python中is和 == 的区别
- Python中is和==的区别
- 剖析OC中的bounds与frame的区别
- 使用child_process创建进程
- NYOJ 236 心急的C小加(贪心)
- 解决Django与AngularJS模板冲突的设置
- 编写通讯录,实现以下四种功能
- Python的is和==区别(整理)
- 阿里云发布案例(持续更新中)
- Java基础编程1—闰年
- Struts2_全局类型转换器
- 使用mybatis时出现问题
- 进程互斥
- UVALive 3942 Trie加速dp
- java 中int是32位,表示的大小范围是31个9?
- 2014年马化腾致业界合作伙伴的公开信