python 函数定位参数+关键字参数+inspect模块

 更新时间:2022年05月13日 11:46:57   作者:wx59129d39de499  
这篇文章主要介绍了python 函数定位参数+关键字参数+inspect模块,文章围绕主题展开详细的相关资料,具有一定的参考价值,需要的小伙伴可以参考一下

函数内省(function introspection)

除了__doc__属性, 函数对象还有很多属性,对于下面的函数,可以使用dir()查看函数具有的属性:

>>> 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__'] 

其中大多数是Python常规类都有的属性,下面重点看看常规对象没有而函数对象有的属性:

>>> 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__']

对于上面列出的函数特有属性,说明如下:

  • __annotations__ dict 参数和返回值的注释
  • __call__ method-wrapper 实现()运算符,即可调用对象的协议
  • __closure__ tuple 函数闭包,即自由变量的绑定(通常是None)
  • __code__ code 编译成字节码的函数元数据和函数定义体
  • __defaults__ tuple 形式参数的默认值
  • __get__ method-wrapper 实现只读描述符协议
  • __globals__ dict 函数所在的模块中的全局变量
  • __kwdefaults__ dict 仅限关键字形式参数的默认值
  • __name__ str 函数名称
  • __qualname__ str 函数的限定名称

定位参数和仅限关键字参数

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'))#定位参数 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 关键字传入 cls='sidebar'
print(tag(content='testing',name='img'))#第一个参数name 也能作为关键字传入
#同名键会绑定到对应的具名参数上,剩余的则会被**attrs捕获
print(tag(**{'name':'img','title':'sunset boulevard','src':'sunset.jpg','cls':'framed'}))
#仅限关键字参数是python3.0新增的特性,在上例中,cls参数只能通过关键字参数指定,他一定不会捕获未命名的定位参数
#定义函数时候,如果想指定仅限关键字参数,要把它们放到*的参数后面
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模块把实参绑定给函数调用:

(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'})>

到此这篇关于python 函数定位参数+关键字参数+inspect模块的文章就介绍到这了,更多相关python inspect模块内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 在Python 中实现图片加框和加字的方法

    在Python 中实现图片加框和加字的方法

    今天小编就为大家分享一篇在Python 中实现图片加框和加字的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-01-01
  • pygame实现贪吃蛇游戏(下)

    pygame实现贪吃蛇游戏(下)

    这篇文章主要为大家介绍了pygame实现贪吃蛇游戏的下篇,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-10-10
  • Python爬取十篇新闻统计TF-IDF

    Python爬取十篇新闻统计TF-IDF

    这篇文章主要为大家详细介绍了Python爬取十篇新闻统计TF-IDF的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-01-01
  • Python检测QQ在线状态的方法

    Python检测QQ在线状态的方法

    这篇文章主要介绍了Python检测QQ在线状态的方法,涉及Python通过第三方平台检测QQ在线状态的技巧,非常简单实用,需要的朋友可以参考下
    2015-05-05
  • Python3中省略号(...)用法介绍

    Python3中省略号(...)用法介绍

    本文主要介绍了Python3中省略号(...)用法介绍,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-02-02
  • 读取本地json文件,解析json(实例讲解)

    读取本地json文件,解析json(实例讲解)

    下面小编就为大家分享一篇读取本地json文件,解析json的实例讲解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2017-12-12
  • python机器学习XGBoost梯度提升决策树的高效且可扩展实现

    python机器学习XGBoost梯度提升决策树的高效且可扩展实现

    这篇文章主要为大家介绍了python机器学习XGBoost梯度提升决策树的高效且可扩展实现,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2024-01-01
  • VS Code配置Anaconda Python环境的详细教程

    VS Code配置Anaconda Python环境的详细教程

    在 Visual Studio Code (VS Code) 中可以使用 Anaconda 环境进行 Python 开发,可以充分利用 Anaconda 提供的包管理和虚拟环境功能,同时享受 VS Code 提供的强大开发工具和调试功能,本文主要介绍了VS Code配置Anaconda Python环境的详细教程,需要的朋友可以参考下
    2024-09-09
  • 基于python实现一个简单的浏览器引擎

    基于python实现一个简单的浏览器引擎

    浏览器引擎是用来处理、渲染和显示网页内容的核心组件,其主要任务是将用户输入的URL所代表的网页资源加载并呈现出来,通常包括HTML、CSS、JavaScript以及各种多媒体内容,本文给大家介绍了如何基于python实现一个简单的浏览器引擎,需要的朋友可以参考下
    2024-10-10
  • 浅析python redis的连接及相关操作

    浅析python redis的连接及相关操作

    Redis是一个开源的使用ANSIC语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。这篇文章主要介绍了python redis的连接及相关操作,需要的朋友可以参考下
    2019-11-11

最新评论