Python a day---difficult to understand the phenomenon + clear explanation---We are all the same

Source: Internet
Author: User

? Deep down, we're all the same *
class WTF:  pass

Output:

>>> WTF() == WTF() # 两个不同的对象不相等False>>> WTF() is WTF() # id一样不相等False>>> hash(WTF()) == hash(WTF()) # 哈希值也“应该”不相等True>>> id(WTF()) == id(WTF())True
Explain:
    • When id a function is used, Python creates an WTF object named and passes it to the id function. The id function gets its id (its memory location) and discards the object.
    • When we do this in the interaction, Python will give the object a new location if it finds an object that occupies an unused memory location.
    • But why use is the comparison results False ? Let's take a look.

      class WTF(object):def __init__(self): print("I") # 创建时触发def __del__(self): print("D") #丢弃时触发

      Output:

      >>> WTF() is WTF()I  # 创建1I  # 创建2,比较,内存位置不同,返回falseD # 删除1D # 删除2False>>> id(WTF()) == id(WTF())I #创建1D #记住内存,连同内存一起删掉I #创建2,它用了1的内存(因为1已经删掉),比较,两个内存相同。D #删除2True

Python a day---difficult to understand the phenomenon + clear explanation---We are all the same

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.