“is” operator not working as intended

后端 未结 3 1179
小鲜肉
小鲜肉 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:51

    WHen you do: print id(check_abcd.search(ti)) in a line and don't store the return value of search anywhere, its reference count goes to zero and it is destroyed. The call in the line bellow that creates another object, which happens to be in the same memory address (which is used by CPython as an object ID) - but it is not the same object.

    When you use the is operator, the previous object still has to exist in order for the comparison to occur, and its address will be different.

    Just put the results of the calls to check_abcd.search in a variable before printing their ID (and use different variables) and you will be able to see what is actually going on.

    Moreover: continuing in these lines can be instructive if you want to learn about the behavior of "is" and object IDs - but if you want to compare strings, and return values, just use the == operator, never is: subsequent function calls, even if returning the same value are not supposed to return the same object - the is comparison is only recommended when comparing with "None" (which is implemented as a singleton)

提交回复
热议问题