python變量
#python和java中的變量本質不一樣,python的變量實質是一個指針 int str,
#便利貼
a=1
a=“abc”
#1.a貼在對象1上
#2.先生成對象,然後將變量指向對象。
a=[1,2,3]
b=a
print(id(a),id(b))
print(a is b)
對象引用參數傳遞經典錯誤
def add(a,b):
a+=b
return a
class Company:
def __init__(self,name,staffs=[]):
self.name=name
self.staffs=staffs
def add(self,staff_name):
self.staffs.append(staff_name)
def remove(self,staff_name):
self.staffs.remove(staff_name)
if __name__=="__main__":
com1=Company("like",["xiapang","xiaohe","m"])
com1.add("music")
com1.remove("m")
print(com1.staffs)#['xiapang', 'xiaohe', 'music']
com2=Company("like2")
com2.add("xiaopang")
print(com2.staffs)#['xiapang', 'xiaohe', 'music']
com3=Company("like3")
com3.add("xiaohe")
print(com2.staffs)#['xiaopang', 'xiaohe']
print(com3.staffs)#['xiaopang', 'xiaohe']
print(com2.staffs is com3.staffs)#True
'''
爲什麼兩個不同的對象com2和com3它們的staffs卻
互相影響了,
1.參數數staffs是列表,是可變對象
2.因爲com2和com3剛開傳參的時候沒有傳遞staffs
這個列表作爲參數,所以內部會調用默認的list,
2個對象都是用的是默認的list
'''
# a=1
# b=2
# c=add(a,b)
# print(c)#3
# print(a,b)#1 2
# a=[1,2]
# b=[3,4]
# c = add(a, b)
# print(c)#[1, 2, 3, 4]
# print(a,b)#[1, 2, 3, 4] [3, 4]
#
# a=(1,2)
# b=(3,4)
# c = add(a, b)
# print(c)#(1, 2, 3, 4)
# print(a,b) #(1, 2) (3, 4)
==和is
a=[1,2,3,4]
b=[1,2,3,4]
print(a==b)#True 會調用__eq__ 來判斷他們的值
print(id(a),id(b)) #167632840 167484552
print(a is b) # False
c=1
d=1
print(id©,id(d)) #1633938544 1633938544
print(c is d)#True
delete和垃圾回收的區別
#cpython2.0中垃圾回收的算法是採用 引用計數
a=object()
b=a
del a
#del並不是回收機制,它是刪除了一個變量
# 的引用,並將其引用計數減1
#而垃圾回收機制則是在引用計數爲0時才進行回收
print(b)
# print(a)
class A:
#當python解釋器要回收的時候,它就可以執行
#__del__ 這個魔法函數裏的邏輯
def __del__(self):
pass