python的count怎么用,python中的count方法

  

  计算机编程语言的反射机制可以动态获取对象信息以及动态调用对象,Python反射介绍介绍了计算机编程语言常用的反射函数使用方法,本文介绍如何获取对象中的函数注释信息以及参数信息。   

  

  定义一个人类:   

  

  class Person(): def talk(自我,姓名,年龄,身高=无): ' ' '谈函数:return: ' ' '打印(f '我的名字是{name} ')打印(f '我的年龄是{年龄} ')如果身高不是None:打印(f '我的身高是{height}')dir()命令也可以获取函数的属性信息:   

  

  Person=Person()print(dir(Person))func=getattr(Person,' talk')print(dir(func))Out:   

  

  __class__ ',' __delattr__ ',' __dict__ ',' __dir__ ',' __doc__ ',' __format__ ',' _ _ getattribute _ _ ',' __gt__ ',' __hash__ ',' __init_subclass__ ',' __le__ ',' __lt__ ',' __module__ ',' __ne__ '获取函数注释信息可以通过__doc__属性来获取注释信息(三引号括起来的注释):   

  

  func=getattr(person,' talk')print(func .__doc__)Out:   

  

  通话功能:返回:获取函数参数1、 通过 __code__ 属性读取函数参数信息   

  

  打印(目录(功能_ _ code _ _)' _ _ class _ _ ',' __delattr__ ',' __dir__ ',' __doc__ ',' __format__ ',' __ge__ ',' __getattribute__ ',' __hash__ ',' __init__ ',' __init_subclass__ ',' __le__ ',' __lt__ ',' __ne__ ',' __new__ '代码_ _。co_name) #返回函数名print('co_argcount: ',func .__代码_ _。co_argcount) #返回函数的参数个数打印(' co_varnames: ',func .__代码_ _。co_varnames) #返回函数的参数打印(' co_filename: ',func .__代码_ _。co_filename) #返回文件绝对路径打印(' co_consts: ',func .__代码_ _。co _ consts)print(' co _ first line no : ',func .__代码_ _。co_firstlineno) #返回函数行号print('co_kwonlyargcount: ',func .__代码_ _。co_kwonlyargcount) #关键字参数打印(' co_nlocals: ',func .__代码_ _。本地电话返回局部变量个数Out:   

  

  co _ name : talk co _ arg count : 4co _ varnames :(' self ',' name ',' age ',' height ')co _ filename :d :/program workspace/Python notes/00-Python-Essentials/demo。pyco _ consts :(' talk function \ n 3360 return : \ n ','我的名字是','我的年龄是,无,'我的身高是)co _第一行编号: 4co _ kwh通过__代码_ _。co_varnames可以获取参数名,参数默认值可以通过如下方式获得:   

  

  打印(功能。__默认值__)Out:   

  

  (无,)2、通过inspect库来读取函数参数信息   

  

  除了用__代码_ _属性外还可以使用检查库来读取函数参数,使用getfullargspec和签名方法来读取函数参数:   

  

  进口检验#检验。getargspec(func)# python 2 arg spec=inspect。getfullargspec(func)print(arg spec。参数)打印(参数规格。默认值)打印(参数规格。varkw)SIG=inspect。签名(功能)打印(签名)输出:   

  

  自我','姓名','年龄','身高(无,)无(姓名,年龄,身高=无)也可以在函数内部使用:   

  

  class Person(): def talk(本人,姓名,年龄,身高=无): ' ' ' talk函数: return : ' ' ' frame=inspect。当前帧()参数,_,_,值=inspect。getargvalues(帧)打印(检查。getframeinfo(frame))print(f '函数名: { inspect。getframeinfo(frame).function } ')for I in args : print(f ' { I }={ values } ')if _ _ name _ _=' _ _ main _ _ ' : p=Person()p . talk('张三,18,height=175) Out:   

  

  回溯(filename=' d :/program workspace/Python notes/00-Python-Essentials/demo。py ',lineno=44,function='talk ',code _ context=' print(inspect。getframeinfo(frame))\ n ',index=0)函数名: talkself=__main__ .0x 0000023 cf 17 b 08 name=张anage=18 height=175的个人对象   

相关文章