Python is与==
2020-02-01 04:40
811 查看
一句话概括
is用于对象引用比较,==用于值比较
实例
>>> t1 = 1024 >>> t2 = 1024 >>> t1 == t2 True >>> t1 is t2 False >>> s1 = 'h%e' >>> s2 = 'h%e' >>> s1 == s2 True >>> s1 is s2 False >>> l1 = [1,2,3] >>> l2 = [1,2,3] >>> l1 == l2 True >>> l1 is l2 False
考虑到Python对0~256的数值,以及常见字符串作了常量池优化,这样指向同一个对象,当使用is判定时结果为True
>>> t1 = 256 >>> t2 = 256 >>> t1 is t2 True >>> s1 = 'hello' >>> s2 = 'hello' >>> s1 is s2 True
重载==(__eq__)
前面的实例,
l1 = [1,2,3]与
l2 = [1,2,3],当比较
l1 == l2是返回True,这是由于内置类型list对象重载了==,也就是实现了
__eq__方法,如下定义了User类,并且重载了
__eq__
>>> class User: ... def __init__(self, name, age): ... self.name = name ... self.age = age ... def __eq__(self, other): ... if not isinstance(other, User): ... return False ... return [self.name, self.age] == [other.name, other.age] ... >>> u1 = User('test',18) >>> u2 = User('test',18) >>> u1 == u2 True >>> u1 is u2 False >>> u3 = User('hello', 18) >>> u4 = User('world', 18) >>> u3 == u4 False >>> u3 is u4 False
转载于:https://my.oschina.net/athantang/blog/1798123
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- python Django 'learing_logs' is not a registered namespace
- Python3运行报错TypeError: Object of type bytes is not JSON serializable
- python中is 与 == 的区别
- python robotframework用法及"wxpython not found"和“no browser is open”问题解决
- python reload(sys)找不到,name 'reload' is not defined和Python3异常-AttributeError: module 'sys' has no att
- python_scrapy_TypeError: 'LuboavSpider' object is not iterable问题及解决
- Python经典面试题 之 is 和 == 的区别
- 成功解决read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and wil
- 成功解决softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be
- Python中运算符"=="和"is"的详解
- Fatal Python error: pycurl: libcurl link-time version is older than compile-time version
- Python程序的错误:变量未定义(NameError: name ‘mesage’ is not defined.)
- python os.path.isfile 的使用误区详解
- Python学习 Day 8 继承 多态 Type isinstance dir __slots__
- Python中is和==的区别
- mac环境下,运行matplotlib时出现ImportError: Python is not installed as a framework
- 【Python】NameError:name ‘xrange’ is not defined
- python3.6.1安装失败:Service Pack 1 is required to continue installation
- finally the popularity of Python is beyond Java
- Windows环境下Python 安装库 is not a supported wheel on this platform解决办法【转】