반응형

== , is 차이점


환경 : windows 8.0 64bit, python 2.7.5 64bit


참고 :  http://stackoverflow.com/a/1085656


== is for value equality. (값 비교)

is is for reference equality. (참조 비교)


 
>>> a = 1234
>>> b = 1234   # a, b  값(1234)은 같다 
>>> 
>>> id(a)
46033040L
>>> 
>>> id(b)    # a, b 참조(id)는 다르다.
46033088L
>>> 
>>> a == b   # 값 비교
True
>>> 
>>> a is b   # 참조 비교
False
>>> 
>>> 







*** 예외 상황 ***


1. 정수형 숫자 (integer caching)

     -5256 까지는 내부적으로 cached 되어있는듯.


      참고 : http://choorucode.com/2012/05/01/integer-caching-in-python/


** 아래 코드를 실행해 보자!!!!!

 
for i in range(-100, 300):
    a = i + 1
    b = int(str(i)) + 1
    if a is b :    # id (참조) 같은 경우
        print '%d is %d'%(a,b), '  --> cached'
 


-- 주의 사항 --

 
>>> 257 is 257   # 잘못된 결과 나온다.
True
>>>

>>> a = 257
>>> b = 257
>>> a is b    # 변수로 비교해야 제대로 결과 나옴.
False
>>>



2. 문자열 

   --- 'string interning' 개념인데, 

          ; "문자열이 처음 생길때 파이썬 내부적으로 table 에 보관하고, 

         같은 문자열을 생성할때 이미 똑같은 문자열이 table 에 있으면

         새로 생성하지 않고, 내부 table 의 참조를 반환하여 같이 사용하게 한다" 는 의미!


   참고 : http://guilload.com/python-string-interning/

            https://docs.python.org/2/library/functions.html#intern

            http://mattyjwilliams.blogspot.kr/2011/12/string-equality-identity-and-interning.html

            http://en.wikipedia.org/wiki/String_interning  ---> 위키 : java, .net 등에서 사용하는 개념이다.

            http://stackoverflow.com/questions/15541404/python-string-interning



 
>>> a = 'abc'
>>> b = 'abc'
>>> a == b
True
>>> a is b    # a, b 가 같은 문자열 참조 (string interning)
True
>>> 
>>> 
>>> c = 'abc!'
>>> d = 'abc!'
>>> c == d
True
>>> c is d    #  c, d 참조가 다르다!!!!  ( 예상과 다른 결과 ???????)
False
>>> 
>>> 
>>> 
>>> m = 'a'*10
>>> mm = 'aaaaaaaaaa'
>>> m == mm
True
>>> m is mm      # m, mm 가 같은 문자열 참조 (string interning)     
True
>>> 
>>> 
>>> n = 'a'*30
>>> nn ='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
>>> n == nn
True
>>> n is nn     #  n, nn 참조가 다르다!!!!  ( 예상과 다른 결과 ???????)
False
>>> id(n)
46363824L
>>> id(nn)
46363312L
>>> 
 


 --- python 2.7.5 에서는 경우에 따라 다른듯. ???



반응형
Posted by 자유프로그램
,