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。
所以想請問一下是為什麼?
python 有一個整數緩存的機制當你在這個範圍 pythom 不會創造一個新的變數而是直接引用