翼度科技»论坛 编程开发 python 查看内容

获取Python函数信息的方法

5

主题

5

帖子

15

积分

新手上路

Rank: 1

积分
15
Python的反射机制可以动态获取对象信息以及动态调用对象,本文介绍如何获取对象中的函数注释信息以及参数信息。
定义一个Person类:
  1. class Person():
  2.     def talk(self, name, age, height=None):
  3.         """talk function
  4.         :return:
  5.         """
  6.         print(f"My name is {name}")
  7.         print(f"My age is {age}")
  8.         if height is not None:
  9.             print(f"My height is {height}")
复制代码
dir() 命令也可以获取函数的属性信息:
  1. person = Person()
  2. print(dir(person))
  3. func = getattr(person, "talk")
  4. print(dir(func))
复制代码
结果
  1. ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'talk']
  2. ['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__func__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
复制代码
获取函数注释信息

可以通过 doc 属性来获取注释信息(三引号括起来的注释):
  1. func = getattr(person, "talk")
  2. print(func.__doc__)
复制代码
结果
  1. talk function
  2.         :return:
复制代码
获取函数参数

1、 通过 __code__ 属性读取函数参数信息
  1. >> print(dir(func.__code__))
  2. ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', 'co_kwonlyargcount', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_stacksize', 'co_varnames']>>
  3. #学习中遇到问题没人解答?小编创建了一个Python学习交流群:725638078
  4. print("co_name: ", func.__code__.co_name)  # 返回函数名
  5. print("co_argcount: ", func.__code__.co_argcount)  # 返回函数的参数个数
  6. print("co_varnames: ",func.__code__.co_varnames) # 返回函数的参数
  7. print("co_filename: ", func.__code__.co_filename) # 返回文件绝对路径
  8. print("co_consts: ", func.__code__.co_consts)
  9. print("co_firstlineno: ",func.__code__.co_firstlineno) # 返回函数行号
  10. print("co_kwonlyargcount: ",func.__code__.co_kwonlyargcount) # 关键字参数
  11. print("co_nlocals: ",func.__code__.co_nlocals) # 返回局部变量个数
复制代码
结果
  1. co_name:  talk
  2. co_argcount:  4
  3. co_varnames:  ('self', 'name', 'age', 'height')
  4. co_filename:  D:/ProgramWorkspace/PythonNotes/00-Python-Essentials/demo.py
  5. co_consts:  ('talk function\n        :return:\n        ', 'My name is ', 'My age is ', None, 'My height is ')
  6. co_firstlineno:  44
  7. co_kwonlyargcount:  0
  8. co_nlocals:  4
复制代码
通过 code.co_varnames 可以获取参数名,参数默认值可以通过如下方式获得:
  1. print(func.__defaults__)
复制代码
结果
  1. (None,)
复制代码
2、通过inspect库来读取函数参数信息

除了用__code__ 属性外还可以使用inspect库来读取函数参数,使用getfullargspec和signature方法来读取函数参数:
  1. import inspect
  2. # inspect.getargspec(func) # python2
  3. argspec = inspect.getfullargspec(func)
  4. print(argspec.args)
  5. print(argspec.defaults)
  6. print(argspec.varkw)
  7. sig = inspect.signature(func)
  8. print(sig)
复制代码
结果
  1. ['self', 'name', 'age', 'height']
  2. (None,)
  3. None
  4. (name, age, height=None)
复制代码
也可以在函数内部使用:
  1. class Person():    def talk(self, name, age, height=None):        """talk function
  2.         :return:        """        frame = inspect.currentframe()        args, _, _, values = inspect.getargvalues(frame)        print(inspect.getframeinfo(frame))        print(f'function name: {inspect.getframeinfo(frame).function}')        for i in args:            print(f"{i} = {values[i]}")if __name__ == '__main__':    p = Person()    p.talk("zhangsan", 18, height=175)        
复制代码
结果
  1. Traceback(filename='D:/ProgramWorkspace/PythonNotes/00-Python-Essentials/demo.py', lineno=44, function='talk', code_context=['        print(inspect.getframeinfo(frame))\n'], index=0)
  2. function name: talk
  3. self = <__main__.Person object at 0x0000023E4CF17B08>
  4. name = zhangsan
  5. age = 18
  6. height = 175
复制代码
来源:https://www.cnblogs.com/python1111/p/17296568.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具