Python中简单对象身份
浮点型:
>>> a=b=4.3
>>> a is b
True
>>> c=4.3
>>> a is c
False
>>> d=1.3+3.0
>>> a is d
False
>>> a is b
True
>>> c=4.3
>>> a is c
False
>>> d=1.3+3.0
>>> a is d
False
整型:
>>> a=b=5
>>> c=5
>>> a is b
True
>>> a is c
True
>>> b is c
True
>>> d=2+3
>>> d
5
>>> a is d
True
>>> c=5
>>> a is b
True
>>> a is c
True
>>> b is c
True
>>> d=2+3
>>> d
5
>>> a is d
True
字符串:
>>> a=b='ab'
>>> a
'ab'
>>> c='a'+'b'
>>> c
'ab'
>>> a is c
True
>>> d='ab'
>>> a is d
True
>>> a
'ab'
>>> c='a'+'b'
>>> c
'ab'
>>> a is c
True
>>> d='ab'
>>> a is d
True
>>> a=1
>>> id(a)
10246672
>>> b=1
>>> id(b)
10246672
>>>
>>> c=1.0
>>> id(c)
11630768
>>> d=1.0
>>> id(d)
13533296
>>> id(a)
10246672
>>> b=1
>>> id(b)
10246672
>>>
>>> c=1.0
>>> id(c)
11630768
>>> d=1.0
>>> id(d)
13533296
在上面的例子中,a和b指向了相同的整数对象,但是c和d没有指向相当的浮点数对象,Python仅缓存简单的整数类型和字符串类型,而且缓存的整数类型的范围是(-1,100),被缓存的对象也会被回收。