iT邦幫忙

1

python == 和copy問題

  • 分享至 

  • xImage
import copy
x = [1, [2, 3]]
y = copy.copy(x)
print(x == y)
print(x is y)
print(x[1] is y[1]) 

結果為
True
False
True

import copy
x = [1, [2, 3]]
y = copy.deepcopy(x)
print(x == y)
print(x is y)
print(x[1] is y[1]) 

結果為
True
False
False

import copy
class Person:
  def __init__(self, name, id):
    self.name = name
    self.id = id
  def printname(self):
    print(self.name)
class Student(Person):
  def __init__(self, name, id):
    super().__init__(name, id)
x = Student("John", '133456')
y = copy.copy(x)
print(x == y)  
print(x is y)

結果為
False
False

import copy
class Person:
  def __init__(self, name, id):
    self.name = name
    self.id = id
  def printname(self):
    print(self.name)
class Student(Person):
  def __init__(self, name, id):
    super().__init__(name, id)
x = Student("John", '133456')
y = copy.deepcopy(x)
print(x==y)
print(x is y)

結果為
False
False

1和2我可以理解,==是看兩邊的值,而is是看兩邊的記憶體位置。
但如果造1和2,3和4應該都是print(x==y)結果為True、print(x is y)結果為False。
所以想請問一下是為什麼?

看更多先前的討論...收起先前的討論...
froce iT邦大師 1 級 ‧ 2024-01-03 00:46:29 檢舉
class的比較,你必須複寫他的魔術方法,否則==也是比較記憶體位址。

https://ideone.com/EsbZPq
好奇問問,範例一根範例二都是一樣的程式碼怎麼輸出會不同?
https://clay-atlas.com/blog/2020/08/04/python-cn-equal-is-difference/
值的關係吧??
alien663 iT邦研究生 5 級 ‧ 2024-01-03 15:16:28 檢舉
Python 是 Pass By Value, Pass by Reference, 還是 Pass by Sharing?

https://medium.com/starbugs/python-%E4%B8%80%E6%AC%A1%E6%90%9E%E6%87%82-pass-by-value-pass-by-reference-%E8%88%87-pass-by-sharing-1873a2c6ac46
jackkjh iT邦新手 5 級 ‧ 2024-01-03 16:59:49 檢舉
範例二的copy.copy是copy.deepcopy打錯了抱歉
froce iT邦大師 1 級 ‧ 2024-01-04 10:45:53 檢舉
等一下,是我理解錯誤還是怎麼了,怎麼其他人回的都是變數傳遞方式,我回的是class的比較方式?
我看問題明明是3、4間的結果不如jackkjh所想啊。

class的比較的話,就純粹是實作時沒覆寫__eq__的魔術方法,在class的話==預設就是比較記憶體位置而已。
從設計上考量的話,class要比值也不太能直接預設比較所有屬性,python的基本資料類型是動態的,要寫的話得考慮太多的狀況,屬性的資料型態、深度...
所以直接比記憶體位置也蠻正常的。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
infinityowohz
iT邦新手 5 級 ‧ 2024-01-03 10:57:43
最佳解答
  1. 我猜你想要打上來的是 y = copy.deepcopy(x)
    在 1. 2. 中 都是去複製 x = [1, [2, 3]] 所以他們比較起來會是一樣的
    但在 3. 4. 中 就算他們內容一樣 但因為是兩個不同的函數生成的 所以記憶體位置不一樣

python 有一個整數緩存的機制當你在這個範圍 pythom 不會創造一個新的變數而是直接引用

jackkjh iT邦新手 5 級 ‧ 2024-01-03 17:05:37 檢舉

謝謝您

我要發表回答

立即登入回答