偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

Python 函數(shù)那不為人知的一面

開發(fā) 后端
通常我們定義一個(gè)函數(shù),然后調(diào)用該函數(shù)時(shí),函數(shù)相關(guān)的代碼才開始執(zhí)行??墒呛芏嗳瞬⒉恢?,當(dāng)我們定義函數(shù)時(shí),一些代碼就開始執(zhí)行了。今天就來說說函數(shù)這個(gè)不為人知的一面。

[[434013]]

通常我們定義一個(gè)函數(shù),然后調(diào)用該函數(shù)時(shí),函數(shù)相關(guān)的代碼才開始執(zhí)行??墒呛芏嗳瞬⒉恢溃?dāng)我們定義函數(shù)時(shí),一些代碼就開始執(zhí)行了。今天就來說說函數(shù)這個(gè)不為人知的一面。

先看一段代碼:

  1. def do_something(opt: print('參數(shù) opt'), arg=print('參數(shù) arg')) -> print('函數(shù)的返回值'): 
  2.     print("do something runing"
  3.  
  4. if __name__ == '__main__'
  5.     pass 

上面的代碼我們定義來一個(gè)函數(shù),但是并沒有調(diào)用它,那么它會(huì)輸出信息嗎?

會(huì)的,參數(shù)里無論是類型提示部分,還是默認(rèn)賦值部分,還是返回值的類型提示,里面的語句都會(huì)被執(zhí)行,結(jié)果如下:

這個(gè)做法我自己是很少見的。把 print 函數(shù)換成打開文件、連接數(shù)據(jù)庫之類的操作,也都會(huì)被執(zhí)行。

不過通常情況下,參數(shù)都是不可變類型,如果傳入可變類型,可能每次的函數(shù)調(diào)用,其結(jié)果都會(huì)被改變,例如:

  1. def do_something(opt: print("參數(shù) opt"), arg=[]) -> print("函數(shù)的返回值"): 
  2.     print("do something runing"
  3.     print(f"{arg = }"
  4.     arg.append(0) 
  5.  
  6.  
  7. if __name__ == "__main__"
  8.     do_something(opt=1) 
  9.     do_something(opt=1) 

運(yùn)行結(jié)果如下:

可以發(fā)現(xiàn),調(diào)用兩次函數(shù) do_something,雖然并沒有傳入 arg 參數(shù),arg 的值已經(jīng)發(fā)送了變化。如果不注意這點(diǎn),可能會(huì)有 bug 發(fā)生。在 Pythcarm 中,會(huì)警告我們 arg 是可變對(duì)象:

如果要獲取函數(shù)的類型提示、默認(rèn)值,可以這樣:

  1. def do_something(opt: 1, arg=2) -> 3: 
  2.     print("do something runing"
  3.     print(f"{arg = }"
  4.     arg.append(0) 
  5.  
  6.  
  7. if __name__ == "__main__"
  8.     print(f"{do_something.__annotations__ = }"
  9.     print(f"{do_something.__defaults__ = }"
  10.  
  11. #do_something.__annotations__ = {'opt': 1, 'return': 3} 
  12. #do_something.__defaults__ = (2,) 

本文轉(zhuǎn)載自微信公眾號(hào)「Python七號(hào)」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系Python七號(hào)公眾號(hào)。

 

責(zé)任編輯:武曉燕 來源: Python七號(hào)
相關(guān)推薦

2013-05-15 10:08:27

2014-04-11 14:22:25

前端前端知識(shí)

2021-06-23 14:12:40

算法隊(duì)列

2015-12-21 09:39:23

2010-08-05 11:14:12

Flex優(yōu)勢

2013-07-16 13:59:15

空姐事件移動(dòng)市場華強(qiáng)北生態(tài)鏈

2020-02-20 12:02:32

Python數(shù)據(jù)函數(shù)

2010-09-03 08:52:38

CSS

2013-08-09 09:27:08

vCentervSphere

2010-04-19 16:09:22

Oracle控制文件

2023-11-09 08:05:40

IDEA開發(fā)工具

2018-11-15 14:52:18

Windows 10Windows升級(jí)

2024-05-17 13:08:46

Python代碼

2011-11-15 10:25:56

IBMWindows

2014-08-18 10:44:31

斯諾登

2011-11-08 13:41:27

蘋果siri人工智能數(shù)據(jù)中心

2017-03-28 08:40:14

2021-02-05 09:58:52

程序員Windows系統(tǒng)

2010-09-06 14:19:54

CSS

2011-10-19 16:19:27

iOS 5蘋果
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)