程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python should use is instead of when judging whether an object is none==

編輯:Python

None It's a singleton object , all None The memory addresses of are the same , So use is Judgment is ok .

If you use == Judgment may be problematic , because == Called __eq__() Methods may be overloaded , The result is not as expected :

class ReloadEq():
def __eq__(self, second_value):
return True
req = ReloadEq()
print(req == None)

Output :

True

besides ,is The time efficiency is also better than == Higher :

import timeit
print(timeit.timeit('None is None',number=10**7))
print(timeit.timeit('None == None',number=10**7))

Output :

0.1993637309933547
0.2477139010006795

because is Just compare the addresses , and == Need to compare values , And it may involve objects that need to be traversed, such as lists , You need to compare each element .

Reference link :https://blog.csdn.net/qq_34152244/article/details/100639985


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved