“is” operator not working as intended

后端 未结 3 1177
小鲜肉
小鲜肉 2021-01-15 12:02

Just have a look at this code:

import re

ti = \"abcd\"
tq = \"abcdef\"
check_abcd = re.compile(\'^abcd\')
print id(check_abcd.search(ti))
print id(check_abc         


        
3条回答
  •  醉话见心
    2021-01-15 12:32

    Martjin has given you the correct answer, but for further clarification here is an annotated version of what's happening in your code:

    # this line creates returns a value from .search(), 
    # prints the id, then DISCARDS the value as you have not 
    # created a reference using a variable.
    print id(check_abcd.search(ti)) 
    
    # this line creates a new, distinct returned value from .search()
    # COINCIDENTALLY reusing the memory address and id of the last one.
    print id(check_abcd.search(tq))
    
    # Same, a NEW value having (by coincidence) the same id
    print check_abcd.search(ti)
    
    # Same again
    print check_abcd.search(tq)
    
    # Here, Python is creating two distinct return values.  
    # The first object cannot be released and the id reused
    # because both values must be held until the conditional statement has 
    # been completely evaluated.  Therefore, while the FIRST value will
    # probably reuse the same id, the second one will have a different id.
    if check_abcd.search(ti) is check_abcd.search(tq):
        print "Matching"
    else:
        print "not matching"
    

提交回复
热议问题