函数自省
函数自省: 函数可以通过__dir__查看函数具有哪些属性
__closure__函数闭包,即自由变量的绑定
__globals__ 函数所在模块中的全局变量
__defaults__ 形参的默认值
__kwdefaults__ only-positional 的默认值
__annotations__ 参数和返回值的注解
__name__ 函数名称
__qualname__ 函数的限定名称
__code__ 编译成字节码的函数元数据和函数定义体
__call__ 可调用对象协议
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | a = 0 def func(b = 1 , * , d = 5 ) - > object : global a c = 0 def inner(): nonlocal c c + = 1 print (c) return inner print ( dir (func)) print (func.__annotations__) # 参数和返回值的注解 print (func.__name__) # 函数名 print (func.__qualname__) # python 3.3后加入 通过类和函数的如何定义的 来确定他们的限定名称 print (func.__call__) # 可调用对象协议 print (func.__code__) # code对象引用 print (func.__code__.co_varnames) # 局部变量 print (func.__code__.co_argcount) # 位置参数个数 print (func.__defaults__) # 参数的默认值 print (func.__kwdefaults__) # 仅限关键字参数的默认值 print (func.__globals__) # 全局变量 函数返回一个全局变量的字典,包括所有导入的变量 g = func() print (g.__closure__) # 函数闭包 即自由变量的绑定 print (g.__code__.co_freevars) # 自由变量 [ '__annotations__' , '__call__' , '__class__' , '__closure__' , '__code__' , '__defaults__' , '__delattr__' , '__dict__' , '__dir__' , '__doc__' , '__eq__' , '__format__' , '__ge__' , '__get__' , '__getattribute__' , '__globals__' , '__gt__' , '__hash__' , '__init__' , '__init_subclass__' , '__kwdefaults__' , '__le__' , '__lt__' , '__module__' , '__name__' , '__ne__' , '__new__' , '__qualname__' , '__reduce__' , '__reduce_ex__' , '__repr__' , '__setattr__' , '__sizeof__' , '__str__' , '__subclasshook__' ] { 'return' : < class 'object' >} func func <method - wrapper '__call__' of function object at 0x0000023B52E966A8 > <code object func at 0x0000023B52E7A150 , file "D:/workspace/Python/练习/test.py" , line 715 > ( 'b' , 'd' , 'inner' ) 1 ( 1 ,) { 'd' : 5 } { '__name__' : '__main__' , '__doc__' : None , '__package__' : None , '__loader__' : <_frozen_importlib_external.SourceFileLoader object at 0x0000023B52C2B4A8 >, '__spec__' : None , '__annotations__' : {}, '__builtins__' : <module 'builtins' (built - in )>, '__file__' : 'D:/workspace/Python/练习/test.py' , '__cached__' : None , '__author__' : 'Frank Shen' , 'a' : 0 , 'requests' : <module 'requests' from 'D:\\anaconda\\lib\\site-packages\\requests\\__init__.py' >, 'choice' : <bound method Random.choice of <random.Random object at 0x0000023B5315E138 >>, 'func' : <function func at 0x0000023B52E966A8 >} <method - wrapper '__get__' of function object at 0x0000023B52E966A8 > (<cell at 0x0000023B53F587F8 : int object at 0x000000005D116C20 >,) ( 'c' ,) |
分类:
Python
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· 趁着过年的时候手搓了一个低代码框架
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· 乌龟冬眠箱湿度监控系统和AI辅助建议功能的实现