網(wǎng)站首頁 編程語言 正文
python?函數(shù)定位參數(shù)+關(guān)鍵字參數(shù)+inspect模塊_python
作者:wx59129d39de499 ? 更新時間: 2022-07-07 編程語言函數(shù)內(nèi)省(function introspection)
除了__doc__屬性, 函數(shù)對象還有很多屬性,對于下面的函數(shù),可以使用dir()查看函數(shù)具有的屬性:
>>> dir(factorial) ['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']?
其中大多數(shù)是Python常規(guī)類都有的屬性,下面重點看看常規(guī)對象沒有而函數(shù)對象有的屬性:
>>> class C:pass
...
>>> obj = C()
>>> def func():pass
...
>>> sorted(set(dir(func)) - set(dir(obj))) # 計算差集,然后排序
['__annotations__', '__call__', '__closure__', '__code__', '__defaults__', '__get__', '__globals__', '__kwdefaults__', '__name__', '__qualname__']
對于上面列出的函數(shù)特有屬性,說明如下:
- __annotations__ dict 參數(shù)和返回值的注釋
- __call__ method-wrapper 實現(xiàn)()運算符,即可調(diào)用對象的協(xié)議
- __closure__ tuple 函數(shù)閉包,即自由變量的綁定(通常是None)
- __code__ code 編譯成字節(jié)碼的函數(shù)元數(shù)據(jù)和函數(shù)定義體
- __defaults__ tuple 形式參數(shù)的默認(rèn)值
- __get__ method-wrapper 實現(xiàn)只讀描述符協(xié)議
- __globals__ dict 函數(shù)所在的模塊中的全局變量
- __kwdefaults__ dict 僅限關(guān)鍵字形式參數(shù)的默認(rèn)值
- __name__ str 函數(shù)名稱
- __qualname__ str 函數(shù)的限定名稱
定位參數(shù)和僅限關(guān)鍵字參數(shù)
def tag(name,*content,cls=None,**attrs):
if cls is not None:
attrs['class'] = cls
if attrs:
attrs_str = ''.join(' %s="%s" ' % (attr,value) for attr,value in sorted(attrs.items()))
else:
attrs_str=''
if content:
return '\n'.join('<%s %s >%s</%s>' % (name,attrs_str,c,name) for c in content)
else:
return '<%s%s />' % (name,attrs_str)
print(tag('br'))#定位參數(shù) name
print(tag('p','hello'))#hello 會被*conteng捕獲 存入元組content = ('hello')
print(tag('p','hello','world'))#content = ('hello','world')
print(tag('p','hello',id=33)) #attrs={'id':33} content = ('hello')
print(tag('p','hello','world',cls='sidebar'))#cls 關(guān)鍵字傳入 cls='sidebar'
print(tag(content='testing',name='img'))#第一個參數(shù)name 也能作為關(guān)鍵字傳入
#同名鍵會綁定到對應(yīng)的具名參數(shù)上,剩余的則會被**attrs捕獲
print(tag(**{'name':'img','title':'sunset boulevard','src':'sunset.jpg','cls':'framed'}))
#僅限關(guān)鍵字參數(shù)是python3.0新增的特性,在上例中,cls參數(shù)只能通過關(guān)鍵字參數(shù)指定,他一定不會捕獲未命名的定位參數(shù)
#定義函數(shù)時候,如果想指定僅限關(guān)鍵字參數(shù),要把它們放到*的參數(shù)后面
def f(a,*,b):
return a,b
ff = f(1,b=2)
print(ff)
<br />
<p >hello</p>
<p >hello</p>
<p >world</p>
<p id="33" >hello</p>
<p class="sidebar" >hello</p>
<p class="sidebar" >world</p>
<img content="testing" />
<img class="framed" src="sunset.jpg" title="sunset boulevard" />
(1, 2)
inspect模板
def tag(name,*content,cls=None,**attrs):
if cls is not None:
attrs['class'] = cls
if attrs:
attrs_str = ''.join(' %s="%s" ' % (attr,value) for attr,value in sorted(attrs.items()))
else:
attrs_str=''
if content:
return '\n'.join('<%s %s >%s</%s>' % (name,attrs_str,c,name) for c in content)
else:
return '<%s%s />' % (name,attrs_str)
import inspect
sig = inspect.signature(tag)
print(sig)
my_tag = {'name':'img','title':'sun long','src':'sunlong.jpg','cls':'framed'}
bound_args = sig.bind(**my_tag)
for name,value in bound_args.arguments.items():
print(name,'=',value)
print(bound_args)
inspect模塊把實參綁定給函數(shù)調(diào)用:
(name, *content, cls=None, **attrs)
name = img
cls = framed
attrs = {'title': 'sun long', 'src': 'sunlong.jpg'}
<BoundArguments (name='img', cls='framed', attrs={'title': 'sun long', 'src': 'sunlong.jpg'})>
原文鏈接:https://blog.51cto.com/u_12903656/5290389
相關(guān)推薦
- 2022-06-22 Android在Sqlite3中的應(yīng)用及多線程使用數(shù)據(jù)庫的建議(實例代碼)_Android
- 2022-08-26 一篇文章搞懂Go語言中的Context_Golang
- 2023-12-19 CentOS和Ubuntu中防火墻相關(guān)命令
- 2022-11-09 docker容器直接退出如何進入容器調(diào)試模式_docker
- 2022-07-12 手把手教你用Redis?實現(xiàn)點贊功能并且與數(shù)據(jù)庫同步_Redis
- 2022-12-12 C語言中組成不重復(fù)的三位數(shù)問題_C 語言
- 2022-06-07 victoriaMetrics代理性能優(yōu)化問題解析_數(shù)據(jù)庫其它
- 2022-04-23 冷知識:font-size最小12px的誤區(qū)
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支