python標準庫中inspect模塊的簡單說明
inspect 模塊作用
(1).對是否是模塊,框架,函數(shù)等進行類型檢查。
(2).獲取源碼
(3).獲取類或函數(shù)的參數(shù)的信息
以下是官方文檔說明:
inspect模塊提供了幾個有用的函數(shù)來幫助獲取有關(guān)活動對象的信息,例如模塊,類,方法,函數(shù),回溯,框架對象和代碼對象。
例如,它可以幫助您檢查類的內(nèi)容,檢索方法的源代碼,提取和格式化函數(shù)的參數(shù)列表,或獲取顯示詳細回溯所需的所有信息。
inspect
可以 比較輕松 獲取 函數(shù)的參數(shù), 通過 signature(foo).bind(xxx,xxx) 就可以了.
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import inspect
def foo(a, b='ham', *args):
pass
def test(a, *, b):
print(a,b)
if __name__ == '__main__':
ba = inspect.signature(foo).bind(a='spam', b='frank')
ba.apply_defaults()
print(ba.arguments) # ordereddict
# OrderedDict([('a', 'spam'), ('b', 'frank'), ('args', ())])import inspect
def foo(a,b,c,*args,**kw):pass
# 拿到函數(shù) 簽名
sig = inspect.signature(foo)
str(sig)
'(a, b, c, *args, **kw)'
## 綁定部分參數(shù), 返回一個 BoundArguments 對象
sig.bind_partial('frank','165cm')
<BoundArguments (a='frank', b='165cm')>
ba =sig.bind_partial('frank','165cm')
## 對于丟失的參數(shù),可以設(shè)置默認值
ba.apply_defaults()
ba.arguments
OrderedDict([('a', 'frank'), ('b', '165cm'), ('args', ()), ('kw', {})])
## signature 還有一個方法 bind
import inspect
def foo(a,b,c,*args,**kw):pass
sig = inspect.signature(foo)
ba = sig.bind('frank','165cm','hello')
ba
<BoundArguments (a='frank', b='165cm', c='hello')>
ba.arguments
OrderedDict([('a', 'frank'), ('b', '165cm'), ('c', 'hello')])
# 指定默認值
ba.apply_defaults()
ba.arguments
OrderedDict([('a', 'frank'), ('b', '165cm'), ('c', 'hello'), ('args', ()), ('kw', {})])bind 和 bind_partial 區(qū)別
綁定參數(shù)的,如果 用 bind 需要要所有的位置參數(shù) 都要綁定. bind_partial 可以部分進行綁定.
import inspect
def foo(a,b,c,*args,**kw):pass
sig = inspect.signature(foo)
sig
<Signature (a, b, c, *args, **kw)>
sig
<Signature (a, b, c, *args, **kw)>
sig.bind('frank','165cm')
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/inspect.py", line 2968, in bind
return args[0]._bind(args[1:], kwargs)
File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/inspect.py", line 2883, in _bind
raise TypeError(msg) from None
TypeError: missing a required argument: 'c'
不支持 部分綁定參數(shù), 所以會報錯, 可以使用 sig.bind_partial
sig.bind_partial('frank','165cm')
<BoundArguments (a='frank', b='165cm')>The args and kwargs properties can be used to invoke functions:
signature.bind() 返回一個 Boundarguments 對象. 可以通過 args , kwargs 拿到函數(shù)的所有參數(shù).
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import inspect
def test(a, *, b):
print(a, b)
if __name__ == "__main__":
sig = inspect.signature(test)
ba = sig.bind(10, b=20)
test(*ba.args, **ba.kwargs) # 10 20
# The args and kwargs properties can be used to invoke functions 實用方法
用來判斷 函數(shù),類,實例方法, 內(nèi)建方法, function or method等…
def ismodule(object):
def isclass(object):
def ismethod(object):
def ismethoddescriptor(object):
def isfunction(object):
def isbuiltin(object):
def isabstract(object):
def ismethoddescriptor(object):
def isroutine(object):
"""Return true if the object is any kind of function or method."""舉個例子
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@author: Frank
@contact: frank.chang@shoufuyou.com
@file: test_inspect.py
@time: 2018/5/14 下午1:24
"""
from inspect import getmembers, ismethod, isclass, isfunction
def foo(): pass
class Cat(object):
def __init__(self, name='kitty'):
self.name = name
def sayHi(self):
print(self.name + ' says Hi!')
def fun1(self):
print('fun1 is running')
if __name__ == '__main__':
cat = Cat('frank')
cat.sayHi()
print(isclass(cat)) # False
print(isclass(Cat)) # True
print(ismethod(cat.sayHi)) # True
print(isfunction(cat.sayHi)) # False
print(isfunction(foo)) # true
print(ismethod(cat.fun1)) # Truegetmemory
if __name__ == '__main__':
cat = Cat('frank')
# print(getmembers(cat))
for member in getmembers(cat):
print(member) # 結(jié)果如下
# ('__class__', <class '__main__.Cat'>)
# ('__delattr__', <method-wrapper '__delattr__' of Cat object at 0x10b213dd8>)
# ('__dict__', {'name': 'frank'})
# ('__dir__', <built-in method __dir__ of Cat object at 0x10b213dd8>)
# ('__doc__', None)
# ('__eq__', <method-wrapper '__eq__' of Cat object at 0x10b213dd8>)
# ('__format__', <built-in method __format__ of Cat object at 0x10b213dd8>)
# ('__ge__', <method-wrapper '__ge__' of Cat object at 0x10b213dd8>)
# ('__getattribute__', <method-wrapper '__getattribute__' of Cat object at 0x10b213dd8>)
# ('__gt__', <method-wrapper '__gt__' of Cat object at 0x10b213dd8>)
# ('__hash__', <method-wrapper '__hash__' of Cat object at 0x10b213dd8>)
# ('__init__', <bound method Cat.__init__ of <__main__.Cat object at 0x10b213dd8>>)
# ('__init_subclass__', <built-in method __init_subclass__ of type object at 0x7fc8afc24358>)
# ('__le__', <method-wrapper '__le__' of Cat object at 0x10b213dd8>)
# ('__lt__', <method-wrapper '__lt__' of Cat object at 0x10b213dd8>)
# ('__module__', '__main__')
# ('__ne__', <method-wrapper '__ne__' of Cat object at 0x10b213dd8>)
# ('__new__', <built-in method __new__ of type object at 0x10afc86c0>)
# ('__reduce__', <built-in method __reduce__ of Cat object at 0x10b213dd8>)
# ('__reduce_ex__', <built-in method __reduce_ex__ of Cat object at 0x10b213dd8>)
# ('__repr__', <method-wrapper '__repr__' of Cat object at 0x10b213dd8>)
# ('__setattr__', <method-wrapper '__setattr__' of Cat object at 0x10b213dd8>)
# ('__sizeof__', <built-in method __sizeof__ of Cat object at 0x10b213dd8>)
# ('__str__', <method-wrapper '__str__' of Cat object at 0x10b213dd8>)
# ('__subclasshook__', <built-in method __subclasshook__ of type object at 0x7fc8afc24358>)
# ('__weakref__', None)
# ('fun1', <bound method Cat.fun1 of <__main__.Cat object at 0x10b213dd8>>)
# ('name', 'frank')
# ('sayHi', <bound method Cat.sayHi of <__main__.Cat object at 0x10b213dd8>>)
總結(jié)
當然inspect 有很多方法, 比如 獲取源碼這個,這個就我沒有太用過
經(jīng)常用的可能就是我例子給出的,判斷類型,以及拿到函數(shù)的參數(shù),用inspect模塊非常方便,甚至 可以通過這個模塊,拿到函數(shù)的參數(shù),寫一個裝飾器,對函數(shù)參數(shù)進行檢查
到此這篇關(guān)于python標準庫中inspect模塊的簡單說明的文章就介紹到這了,更多相關(guān)python的inspect模塊內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
對python 矩陣轉(zhuǎn)置transpose的實例講解
下面小編就為大家分享一篇對python 矩陣轉(zhuǎn)置transpose的實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04
查找python項目依賴并生成requirements.txt的方法
今天小編就為大家分享一篇查找python項目依賴并生成requirements.txt的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07
tensorflow模型文件(ckpt)轉(zhuǎn)pb文件的方法(不知道輸出節(jié)點名)
這篇文章主要介紹了tensorflow模型文件(ckpt)轉(zhuǎn)pb文件(不知道輸出節(jié)點名),本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04
Python環(huán)境的安裝以及PyCharm編輯器配置教程詳解
優(yōu)質(zhì)的教程可以讓我們少走很多彎路,這一點毋庸置疑。這篇文章主要為大家介紹了純凈Python環(huán)境的安裝以及PyCharm編輯器的配置,需要的可以參考一下2023-04-04
Python實現(xiàn)桶排序與快速排序算法結(jié)合應(yīng)用示例
這篇文章主要介紹了Python實現(xiàn)桶排序與快速排序算法結(jié)合應(yīng)用,結(jié)合實例形式分析了Python快速排序及桶排序結(jié)合應(yīng)用的相關(guān)實現(xiàn)技巧,需要的朋友可以參考下2017-11-11

