python中None,is和==的深入探討
https://zhuanlan.zhihu.com/p/453647757
a = "hello"
b = "hello"
print(a is b) # 輸出 True
print(a == b) # 輸出 True
print("=" * 30)
a = "hello world aaasdf"
b = "hello world aaasdf"
print(a is b) # 輸出 False (實(shí)際測試是True)
print(a == b) # 輸出 True
print("=" * 30)
a = [1, 2, 3]
b = [1, 2, 3]
print(a is b) # 輸出 False
print(a == b) # 輸出 True
print("=" * 30)
a = [1, 2, 3]
b = a
print(a is b) # 輸出 True
print(a == b) # 輸出 True
print("=" * 30)
# 在使用 a is b 的時候端圈,相當(dāng)于id(a)==id(b)
# == 是值相等嘿期,相當(dāng)于調(diào)用__eq__()方法疚膊,即 a==b ==> a.__eq__(b)
Python中進(jìn)行None判斷時忽舟,為什么用is而不是==
https://zhuanlan.zhihu.com/p/80096499
# is None: 判斷內(nèi)存地址是否一致
# == None: 如果__eq__被重載結(jié)果就不一定了随闺,要根據(jù)重載的__eq__判斷返回什么
class test():
def __eq__(self, other):
return True
t = test()
print(t is None) # False
print(t == None) # True
# 'is'的效率優(yōu)于'=='日川,因?yàn)?is'不能被重載,執(zhí)行'is'只是簡單的獲取對象id