在《關於Python鏈式賦值的賦值順序問題》的評論中,博友“碼哥yoo_____”提醒,上面博文內容的說法還是有問題,正取的說法應該是:
a=b=c=d
賦值處理過程如下:
temp = d
a = temp
b=temp
c=temp
老猿進行了驗證,發現確實如期所說。具體證明方法如下:
class example:
def __init__(self,name):
self.name = name
self.val = 0
self.visitCount = 0
def getValue(self):
self.visitCount += 1
print("getValue exuted:",self.__repr__())
return self.val
def setValue(self,val):
self.val = val
print("setValue exuted:",self.__repr__())
def __repr__(self):
return f"objectName = {self.name},val = {self.val},visitCount={self.visitCount}"
value = property(getValue, setValue,None)
a = example("a")
b = example("b")
c=example("c")
d = example("d")
d.value = 10
a.value=b.value=c.value=d.value
執行截圖:
可以看到執行鏈式賦值語句:a.value=b.value=c.value=d.value
時,先從d對象取值出來後,再也沒有從其他對象取值,然後依次執行a、b、c的賦值。
沒想到一個小小的鏈式賦值出了2次錯,在此再次感謝兩位熱心的博友。
上述證明方法用到了《第7.23節 Python使用property函數定義屬性簡化屬性訪問的代碼實現》和《第7.24節 Python案例詳解:使用property函數定義屬性簡化屬性訪問代碼實現》介紹的知識。不瞭解相關知識的請參考上述兩文。