- 變量 和 數據 都是保存在 內存 中的
- 在
Python
中 函數 的 參數傳遞 以及 返回值 都是靠 引用 傳遞的
在 Python
中python
id()
函數能夠查看變量中保存數據所在的 內存地址注意:若是變量已經被定義,當給一個變量賦值的時候,本質上是 修改了數據的引用算法
- 變量 再也不 對以前的數據引用
- 變量 改成 對新賦值的數據引用
變量引用
的示例在 Python
中,變量的名字相似於 便籤紙 貼在 數據 上app
a
,而且賦值爲 1
代碼 | 圖示 |
---|---|
a = 1 | |
a
賦值爲 2
代碼 | 圖示 |
---|---|
a = 2 | |
b
,而且將變量 a
的值賦值給 b
代碼 | 圖示 |
---|---|
b = a | |
變量
b
是第 2 個貼在數字2
上的標籤函數
在 Python
中,函數的 實參/返回值 都是是靠 引用 來傳遞來的3d
def test(num): print("-" * 50) print("%d 在函數內的內存地址是 %x" % (num, id(num))) result = 100 print("返回值 %d 在內存中的地址是 %x" % (result, id(result))) print("-" * 50) return result a = 10 print("調用函數前 內存地址是 %x" % id(a)) r = test(a) print("調用函數後 實參內存地址是 %x" % id(a)) print("調用函數後 返回值內存地址是 %x" % id(r))
int
, bool
, float
, complex
, long(2.x)
str
tuple
list
dict
a = 1 a = "hello" a = [1, 2, 3] a = [3, 2, 1]
demo_list = [1, 2, 3] print("定義列表後的內存地址 %d" % id(demo_list)) demo_list.append(999) demo_list.pop(0) demo_list.remove(2) demo_list[0] = 10 print("修改數據後的內存地址 %d" % id(demo_list)) demo_dict = {"name": "小明"} print("定義字典後的內存地址 %d" % id(demo_dict)) demo_dict["age"] = 18 demo_dict.pop("name") demo_dict["name"] = "老王" print("修改數據後的內存地址 %d" % id(demo_dict))
注意:字典的
key
只能使用不可變類型的數據code
注意blog
(hash)
Python
中內置有一個名字叫作 hash(o)
的函數
哈希
是一種 算法,其做用就是提取數據的 特徵碼(指紋)
Python
中,設置字典的 鍵值對 時,會首先對 key
進行 hash
已決定如何在內存中保存字典的數據,以方便 後續 對字典的操做:增、刪、改、查
key
必須是不可變類型數據value
能夠是任意類型的數據提示:在其餘的開發語言中,大多 不推薦使用全局變量 —— 可變範圍太大,致使程序很差維護!生命週期
def demo1(): num = 10 print(num) num = 20 print("修改後 %d" % num) def demo2(): num = 100 print(num) demo1() demo2() print("over")
# 定義一個全局變量 num = 10 def demo1(): print(num) def demo2(): print(num) demo1() demo2() print("over")
注意:函數執行時,須要處理變量時 會:內存
全局變量的引用
提示:在其餘的開發語言中,大多 不推薦使用全局變量 —— 可變範圍太大,致使程序很差維護!開發
num = 10 def demo1(): print("demo1" + "-" * 50) # 只是定義了一個局部變量,不會修改到全局變量,只是變量名相同而已 num = 100 print(num) def demo2(): print("demo2" + "-" * 50) print(num) demo1() demo2() print("over")
注意:只是在函數內部定義了一個局部變量而已,只是變量名相同 —— 在函數內部不能直接修改全局變量的值
global
進行聲明num = 10 def demo1(): print("demo1" + "-" * 50) # global 關鍵字,告訴 Python 解釋器 num 是一個全局變量 global num # 只是定義了一個局部變量,不會修改到全局變量,只是變量名相同而已 num = 100 print(num) def demo2(): print("demo2" + "-" * 50) print(num) demo1() demo2() print("over")
a = 10 def demo(): print("%d" % a) print("%d" % b) print("%d" % c) b = 20 demo() c = 30
注意
代碼結構示意圖以下
g_
或者 gl_
的前綴提示:具體的要求格式,各公司要求可能會有些差別