Python混合類型計算中的一點疑惑?

在python中如果一個計算表達式中包含不同的類型,計算的背後需要對類型進行轉換,例如整型轉換為浮點型,2轉換為2.0.。但是數值類型不是原子類型,也就是說不存在對一個數值類型變數的更新,而是一個新對象的創建和舊對象的失效,並且被GC回收。那麼問題來了(使用我當前解釋器下的一個例子):

a=2

b=3.5

print(id(a),id(b))

輸出的結果為:1560203744 41769760

c=a+b

print(id(a),id(b))

輸出結果為:1560203744 41769760

結果顯示a的id並沒有發生變化,請問這是為什麼?


python的這些運算符(加減乘除)本質上是function,你用c = a + b其實是在引用__add__這個function,你講的整型轉換為浮點型都在__add__這個function裡面不會影響到外面的a,所以id(a)加之前和加之後是一樣的

&>&>&> a = 2
&>&>&> dir(a)
["__abs__", "__add__", "__and__", "__class__", "__cmp__", "__coerce__", "__delattr__", "__div__", "__divmod__", "__doc__", "__float__", "__floordiv__", "__format__", "__getattribute__", "__getnewargs__", "__hash__", "__hex__", "__index__", "__init__", "__int__", "__invert__", "__long__", "__lshift__", "__mod__", "__mul__", "__neg__", "__new__", "__nonzero__", "__oct__", "__or__", "__pos__", "__pow__", "__radd__", "__rand__", "__rdiv__", "__rdivmod__", "__reduce__", "__reduce_ex__", "__repr__", "__rfloordiv__", "__rlshift__", "__rmod__", "__rmul__", "__ror__", "__rpow__", "__rrshift__", "__rshift__", "__rsub__", "__rtruediv__", "__rxor__", "__setattr__", "__sizeof__", "__str__", "__sub__", "__subclasshook__", "__truediv__", "__trunc__", "__xor__", "bit_length", "conjugate", "denominator", "imag", "numerator", "real"]


推薦閱讀:

Python 3.6 有什麼新特性?
Python2轉Python3有沒有必要重新學習?
VPS 如何搭建 Python 環境?
為什麼 Python 不用 C++ 實現?
Python為什麼直接運行和在命令行運行同樣語句但結果卻不同,他們的緩存機制不同嗎?

TAG:Python | 腳本語言 |