1. Python變量究竟是什麼?python
Python和Java中的變量本質不同,python的變量實質是一個指針 int str,便利貼app
a = 1函數
# 1. a貼在1上面優化
# 2. 它的過程是先生成對象,而後貼便利貼。spa
# 3. is 是指的標籤貼是否同樣。指針
a = 1code
b = 1 對象
這個是同樣,用的是小整數的內部inter機制的內部優化。blog
== 用的是__eq__這個魔法函數。rem
# 4. 經常使用的用法是isinstance或者type() is,這兩種是通用的。type其實是指向了這個對象的。
2. del語句和垃圾回收的關係:
py中的垃圾回收採用的是引用計數。
# a = 1 # b = a # del a # 引用計數器減去1,等於0的時候py會回收。 a = object() b = a del a print(b) # b能夠打印,a打印不出來了 print(a) # C:\Python37\python.exe F:/QUANT/練習/chapter01/type_object_class.py # Traceback (most recent call last): # File "F:/QUANT/練習/chapter01/type_object_class.py", line 9, in <module> # print(a) # NameError: name 'a' is not defined # <object object at 0x000002909F4AAA70> # # Process finished with exit code 1 class A: del __del__(self): pass
記住:對應的魔法函數是__del__
3. 默認空的list的可變,一個景點的參數傳遞問題。
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__': # a = 1 # b = 2 # c = add(a,b) # print(c) # print(a,b) # 3 # 1 2 # a = [1,2] # b = [3,4] # c = add(a,b) # print(c) # print(a,b) # [1, 2, 3, 4] # [1, 2, 3, 4][3, 4] # a = (1,2) # b = (3,4) # c = add(a,b) # print(c) # print(a,b) # (1, 2, 3, 4) # (1, 2) (3, 4) com1 = Company("con1",["bobby1","bobby2"]) com1.add("bobby3") com1.remove("bobby1") print(com1.staffs) # ['bobby2', 'bobby3'] com2 = Company("com2") com2.add("bobby") print(com2.staffs) # ['bobby'] com3 = Company("com3") com3.add("bobby5") print(com2.staffs,com3.staffs) # ['bobby', 'bobby5']['bobby', 'bobby5'] print(com2.staffs is com3.staffs) # True # 這個緣由是運用了一個可變對象=[] print(Company.__init__.__defaults__)
記住:在類中可變對象的話容易形成錯誤的,把a就行修改掉了。
記住:其實這裏就是引用參數的問題。引用參數是用可變對象來實現的。