loop
code
1
2
3
4>items():pass
>
>y
>{'a': 1, 'b': 2}
analysis
1
2
3
4
5
6>x.iterms() # (('a', 1), ('b', 2))
>k = 'a'
>y['a'] = 1
>pass
>k = 'b'
>y['b'] = 2
bool
code
1
2
3
4>"Hello" + True
>TypeError: Can't convert 'bool' object to str implicitly
>"Hello" * True
>'Hello'
analysis
1
2>int(True) # True 真實值爲1,參見python C源碼定義, True就是整型的特殊值.
>1
hash
code
1
2
3
4>def greet(): return
>d = {greet: 1}
>d
>{<function __main__.greet>: 1}
analysis
1
2>hasattr(greet, '__hash__') # True
>greet.__hash__() # -9223363285414220592
int
1
2
3
4
5
6
7
8>x = 1
>y = 1
>x is y
>True
>x = 999
>y = 999
>x is y
>False
analysis
詭異?
其實python在初始化的時候就把一部分整型對象生成好了(這個叫小整型對象池),
但是不可能所有的都生成,官方會測試出一個最佳值來在源碼中寫死;
大於其值,則重新生成,小於等於則直接返回給你,所以,你懂得.
999明顯大於,而1,明顯是直接返回的,只是內部引用增加了而已
正常編譯應該是[-5,256].
測試代碼:
1
2
3
4>x = -5
>x is int(str(x)) # False
>test_int = lambda x: x is int(str(x))
>test_int(256) # True
tuple
code
1
2
3
4
5
6
7>a = [1, 0]
>a[0], a[a[0]] = a[a[0]], a[0]
>a
>[1, 0]
>a[a[0]], a[0] = a[0], a[a[0]]
>a
>[0, 1]
analysis
不好理解?其實就是表達式看起來復雜了點兒,道理很簡單,看代碼
1
2
3
4
5>a[0], a[a[0]] = a[a[0]], a[0]
>>a[0] = a[a[0]]; a[a[0]] = a[0]
>>>a[0] = a[1] # a[0]=0; a[0] = 1 # a-->[1, 0]
>a[a[0]], a[0] = a[0], a[a[0]]
>>a[1] = 1; a[0] = a[1] # a-->[0, 1]