初學Python,貽笑大方。
今天遇到一坑,涉及到字典(dict)作為參數傳入方法內時的操作,和更新字典內容兩方面內容。
首先第一點:
我們來對比一下一組代碼:
代碼A:
# 添加默認字段 def setInsertModel(opt_user_id, dic): # 默認字段元組 common_dic = { 'del_flg': consts.CommonFlg.COM_FLG_OFF.value, 'creator_id': opt_user_id, 'create_dt': DateUtils.getNow(), 'updater_id': opt_user_id, 'update_dt': DateUtils.getNow(), } # 添加默認字段 dic.update(common_dic)
代碼B:
# 添加默認字段 def setInsertModel(opt_user_id, **dic): # 默認字段元組 common_dic = { 'del_flg': consts.CommonFlg.COM_FLG_OFF.value, 'creator_id': opt_user_id, 'create_dt': DateUtils.getNow(), 'updater_id': opt_user_id, 'update_dt': DateUtils.getNow(), } # 添加默認字段 dic.update(common_dic)
僅僅是方法參數定義時加了雙星號(**,代表收集到的參數在方法中作為元組使用),但是結果不同。
中間的代碼就不貼出來了,省的丟人。下面是model更新后的結果:

第二條數據是代碼B執行后的結果,而第一條與第三條數據則是代碼A執行后的結果。這說明作為參數的dic,在代碼A中並沒有被修改。
現在作為初學者簡單的認為是參數的作用域的問題,用雙星號定義的字典,僅僅作為收集參數用的形參,作用域僅在本方法內部,出了方法體就沒人認識這個dic的東西了;相反代碼B中的dic就是原字典的引用,我對這個字典進行操作后,會直接作用到這個字典中,所以代碼B會將默認的字段都添加到需要更新的字典中。如果說的不對,歡迎指教。
那么接下來第二點:
這個就真的比較小兒科了,還是來比較一段代碼:
代碼C:
# 添加默認字段 def setInsertModel(opt_user_id, dic): # 默認字段元組 common_dic = { 'del_flg': consts.CommonFlg.COM_FLG_OFF.value, 'creator_id': opt_user_id, 'create_dt': DateUtils.getNow(), 'updater_id': opt_user_id, 'update_dt': DateUtils.getNow(), } # 添加默認字段 dic.update(common_dic)
代碼D:
# 添加默認字段 def setInsertModel(opt_user_id, dic): # 默認字段元組 common_dic = { 'del_flg': consts.CommonFlg.COM_FLG_OFF.value, 'creator_id': opt_user_id, 'create_dt': DateUtils.getNow(), 'updater_id': opt_user_id, 'update_dt': DateUtils.getNow(), } # 添加默認字段 dic = dic.update(common_dic) return dic
代碼D在執行插入操作時直接報錯了,TypeError:‘NoneType’。其實道理非常簡單,因為dict.update()方法沒有返回值,dic被賦了NoneType,當然報錯了。
