看板 Python 關於我們 聯絡資訊
: 啊你的認知就是錯的啊, 我就說 Google 就有一堆資料了你都沒有在聽嘛 : https://www.google.com.tw/?q=python+call+by+reference : 就看前五個結果好不好 : 1. https://stackoverflow.com/questions/986006 : 這個上面也有提到, 直接看 accepted answer (同時也是分數最高) : Arguments are passed by assignment. [...] the parameter passed in is : actually a reference to an object (but the reference is passed by value). 謝謝你人真好~ <3 我要的就是第一個 link 連到官方的說明。 Remember that arguments are passed by assignment in Python. 官方的文件直接解釋了原原文的三個問題。 --- 一般的認知是: - 對 mutable object 來說它是 pass by object reference (link 4 & 5) - 對 immutable object 來說它是 pass by value Q: so is it passed by reference/value ? 嚴格來說都不是。官方的說法是 passed by assignment. 就我所知 by ref/value 的來源是 .NET 家族的 ref 關鍵字(C#, ByRef for VB),用 C# pass by reference 去找就會看到官方的 Programming Guide. (https://goo.gl/QNh2W4 ) 這裡有一個延伸用物件實作的例子: https://repl.it/J8Us/0 - Python 並沒有 by reference 這件事, by assignment 所在乎的是 mutability. (這也是為什麼官方文件會另外實作 class callByRef) - 相對而言,有 by reference 表示沒有 immutable object 這種東西。 (things can be changed by reference.) * builtin types 實質上也是 mutable 的(in C),這也是為什麼 string 比較相等 性的時候得用 == 而不是 is 。 ( bool 是 builtin constants) -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 192.19.253.250 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1500448247.A.315.html
ckc1ark: 用==和is來比較跟mutable有什麼關係嗎 07/19 16:25
is 是比較物件相等性(id()), == 是比較內容相等性(__eq__); immutable 物件 在操作的時候會隱性的被 reassign 成另外一個物件,所以得用 == 來比較 built-in 的 immutable 物件。 None, True 跟 False 也是 immutable 物件,但它被實作成 const ,所以用 is 或是 == 來比較都可以。 (一般建議是用 is) 我記得沒錯的話 effective java 第三章是在講這個,有興趣可以看一下。
LessonWang: 因為用is的話 是看他們參考到的記憶體位址是否一樣 而 07/19 16:52
LessonWang: 用==只是看實質內容是否一樣 07/19 16:52
LessonWang: a='abc' b=a c='abc' 07/19 16:54
LessonWang: a is b ->True 07/19 16:54
LessonWang: a == b ->True 07/19 16:54
LessonWang: a is c ->False 07/19 16:54
LessonWang: a == c ->True 07/19 16:54
LessonWang: id(a) == id(b) ->True 07/19 16:55
LessonWang: 我都用id來看位址是否一樣 07/19 16:55
LessonWang: 不過 我還是得感謝u大和z大的整理和討論 07/19 16:56
※ 編輯: zerof (203.77.72.241), 07/21/2017 21:26:21
ckc1ark: 可以說一個和string不一樣 實質上不是mutable的case嗎? 07/22 11:52
ckc1ark: 好像只有你說的boolean算是? 07/22 11:54
zerof: int 也是 immutable 喔 07/23 11:13
ckc1ark: int也是用==在比較耶 用is只有-1~256可以而已 07/23 11:35
看錯你的問題... immutable 且 " 行為和 string 不一樣 " 的例子,除了 bool 以外, builtin constants 都是。但我不覺得行為和 string 不一樣就是了... 可以 用 is 來比較的原因是它是 constants ,所以用 == 比較的結果和 is 比較的結果是 一樣的。 ※ 編輯: zerof (203.77.72.241), 07/23/2017 21:13:15
ckc1ark: 不好意思有點久沒看到 我的疑問就是 int和string一樣都是 07/28 01:56
ckc1ark: 要用==不能用is 所以int的case和string不同嗎? 實質上是? 07/28 01:57
ckc1ark: 我的想法是"實質上是mutable"並不是用==和is比較的原因 07/28 01:59
ckc1ark: 是原本就是兩個放在不同記憶體的物件 也就是id不同 07/28 01:59
zerof: 呃...你就視為一樣就好了 07/28 23:17