Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

python - is & == #212

Open
3 tasks
junxnone opened this issue Jun 28, 2020 · 0 comments
Open
3 tasks

python - is & == #212

junxnone opened this issue Jun 28, 2020 · 0 comments

Comments

@junxnone
Copy link
Owner

junxnone commented Jun 28, 2020

Reference

Brief

name Description
is 身份判断符,判断两个对象是否为同一对象
== 等值判断,判断两个对象是否内容相等

Example

  • 所有长度为0和1的字符串都会被驻留
  • 字符串在编译时被实现的会被驻留(如'str'会被驻留,但是 ''.join(['s', 't', 'r']) 不会)
  • 字符串中只包含ASCII下的字母、数字和下划线时会被驻留. 所以'str!'由于包含!不会被驻留
In [1]: a = 'Test'
In [2]: b = 'Test'
In [3]: a is b
Out[3]: True
In [4]: a is 'Test'
Out[4]: True
In [5]: c = 'Test!'
In [6]: d = 'Test!'
In [7]: c is d
Out[7]: False
In [8]: c is 'Test!'
Out[8]: False
In [9]: print(id(a))
140400778717760
In [10]: print(id(b))
140400778717760
In [11]: print(id(c))
140400777527680
In [12]: print(id(d))
140400777530536
In [13]: c == d
Out[13]: True
In [14]: e = '!'
In [15]: f = '!'
In [16]: e is f
Out[16]: True
  • 特殊字符不驻留
In [17]: print(id('Test!'))
140400777708800
In [18]: print(id('Test!'))
140400777710368
In [19]: print(id('Test!'))
140400776986552
In [20]: print(id('Test!'))
140400776969328
  • None是一个特殊的常量,不同的 None 的id是一样的。
In [8]: c = None
In [9]: print(id(c))
10306432
In [10]: print(id(None))
10306432
In [11]: c is None
Out[11]: True
  • 对于整数对象,如果其值处于[-5,256]的闭区间内,则值相同的对象是同一个对象,否则为不同对象
In [26]: print(id(1))
10914496
In [27]: print(id(1))
10914496
In [28]: print(id(1))
10914496
In [29]: print(id(257))
140400778124592
In [30]: print(id(257))
140400779126896
In [31]: print(id(257))
140400778124592
In [32]: print(id(257))
140400779127536
In [33]: print(id(257))
140400778125104
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant