網站首頁 編程語言 正文
函數的特性:
- 函數是對象
- 函數可以刪除
- 函數名字和函數本身完全是分開的
- 函數因為是對象,可以結合數據結構使用
- 函數因為是對象,可以作為函數參數
- 函數因為是對象,可以在嵌套在函數體內
- 內層函數對象能夠記憶住父函數的變量
- 所有的函數都是對象,但是所有的對象并不一定都是函數
對象成為函數需要實現__call__協議
函數是對象:
# 函數是對象:支持賦值操作。 def test1(n): print(f"hello, {n}!") # test1的函數名賦值給 new1 new1 = test1 new1("tom") # hello, tom!
函數可以刪除:
# 函數可以刪除 def test2(n): print(f"hello, {n}!") del test2 # test2("tom") # NameError: name 'test2' is not defined
函數名字和函數本身完全是分開的:刪除test3,不影響已經賦值的new3的調用
# 函數名字和函數本身完全是分開的:刪除test3,不影響已經賦值的調用 def test3(n): print(f"hello, {n}!") new3 = test3 del test3 new3("Jam") # hello, Jam!
函數因為是對象,可以結合數據結構使用:
# 函數因為是對象,就可以結合數據結構使用 def test4(n): print(f"hello, {n}!") data = [1, "a", {"name": "tom"}, test4] for i in data: from types import FunctionType if type(i) == FunctionType: test4("Lily") # hello, Lily!
函數因為是對象,可以作為函數參數:
# 函數因為是對象,就可以作為函數參數 def test5(n): print("原始函數執行") print(f"hello, {n}") def new5(n): n("Golang") new5(test5) # 原始函數執行 hello, Golang
函數因為是對象,可以在嵌套在函數體內:
# 函數因為是對象,可以在嵌套在函數體內 def test6(n): def inner1(m): new = m + "!!!" return new def inner2(m): new = m + "***" return new if n > 3: return inner2 else: return inner1 result6 = test6(3) print(result6("tom")) # tom!!!
內層函數對象能夠記憶住父函數的變量:也稱為閉包
# 內層函數對象能夠記憶住父函數的變量 def test7(n): def inner(m): return m + n return inner result7 = test7(7) print(result7(6)) # 13
所有的函數都是對象,但是所有的對象并不一定都是函數:
# 所有的函數都是對象,但是所有的對象并不一定都是函數 class A: pass a = A() def test8(): pass from types import FunctionType print(isinstance(a, A)) # True print(isinstance(test8, FunctionType)) # True print(isinstance(a, FunctionType)) # False 所有的對象并不一定都是函數
對象成為函數需要實現__call__協議:
# 對象成為函數需要實現__call__協議 class B: def __init__(self, n): self.n = n def __call__(self, m): return self.n + m b = B(9) print(b(9)) # 18
總結
原文鏈接:https://blog.csdn.net/hzblucky1314/article/details/122659958
相關推薦
- 2022-06-13 docker從安裝入門到應用部署及私有倉庫搭建基礎命令_docker
- 2023-01-19 Retrofit?創建網絡請求接口實例過程_Android
- 2022-09-05 Redis 數據刪除策略
- 2023-01-02 Kotlin?RadioGroup與ViewPager實現底層分頁按鈕方法_Android
- 2023-07-27 el-select下拉框處理分頁數據,觸底加載更多
- 2022-06-17 GO語言協程互斥鎖Mutex和讀寫鎖RWMutex用法實例詳解_Golang
- 2023-08-12 thinkadmin 單頁面多個富文本初始化
- 2024-03-20 mybatis-plus不同類型多源數據庫分頁攔截器配置
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支