首页 > 编程语言 >获取Python函数信息的方法

获取Python函数信息的方法

时间:2023-04-07 16:23:54浏览次数:31  
标签:__ code co 函数 Python 获取 func print name

Python的反射机制可以动态获取对象信息以及动态调用对象,本文介绍如何获取对象中的函数注释信息以及参数信息。

定义一个Person类:

class Person():
    def talk(self, name, age, height=None):
        """talk function
        :return:
        """
        print(f"My name is {name}")
        print(f"My age is {age}")
        if height is not None:
            print(f"My height is {height}")

dir() 命令也可以获取函数的属性信息:

person = Person()
print(dir(person))

func = getattr(person, "talk")
print(dir(func))

结果

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

['__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 属性来获取注释信息(三引号括起来的注释):

func = getattr(person, "talk")
print(func.__doc__)

结果

talk function
        :return:

获取函数参数

1、 通过 __code__ 属性读取函数参数信息

>> print(dir(func.__code__))
['__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']>>

#学习中遇到问题没人解答?小编创建了一个Python学习交流群:725638078
print("co_name: ", func.__code__.co_name)  # 返回函数名
print("co_argcount: ", func.__code__.co_argcount)  # 返回函数的参数个数
print("co_varnames: ",func.__code__.co_varnames) # 返回函数的参数
print("co_filename: ", func.__code__.co_filename) # 返回文件绝对路径
print("co_consts: ", func.__code__.co_consts)
print("co_firstlineno: ",func.__code__.co_firstlineno) # 返回函数行号
print("co_kwonlyargcount: ",func.__code__.co_kwonlyargcount) # 关键字参数
print("co_nlocals: ",func.__code__.co_nlocals) # 返回局部变量个数

结果

co_name:  talk
co_argcount:  4
co_varnames:  ('self', 'name', 'age', 'height')
co_filename:  D:/ProgramWorkspace/PythonNotes/00-Python-Essentials/demo.py
co_consts:  ('talk function\n        :return:\n        ', 'My name is ', 'My age is ', None, 'My height is ')
co_firstlineno:  44
co_kwonlyargcount:  0
co_nlocals:  4

通过 code.co_varnames 可以获取参数名,参数默认值可以通过如下方式获得:

print(func.__defaults__)

结果

(None,)

2、通过inspect库来读取函数参数信息

除了用__code__ 属性外还可以使用inspect库来读取函数参数,使用getfullargspec和signature方法来读取函数参数:

import inspect

# inspect.getargspec(func) # python2
argspec = inspect.getfullargspec(func)
print(argspec.args)
print(argspec.defaults)
print(argspec.varkw)
sig = inspect.signature(func)
print(sig)

结果

['self', 'name', 'age', 'height']
(None,)
None
(name, age, height=None)

也可以在函数内部使用:

class Person():
    def talk(self, name, age, height=None):
        """talk function
        :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)        

结果

Traceback(filename='D:/ProgramWorkspace/PythonNotes/00-Python-Essentials/demo.py', lineno=44, function='talk', code_context=['        print(inspect.getframeinfo(frame))\n'], index=0)
function name: talk
self = <__main__.Person object at 0x0000023E4CF17B08>
name = zhangsan
age = 18
height = 175

标签:__,code,co,函数,Python,获取,func,print,name
From: https://www.cnblogs.com/python1111/p/17296568.html

相关文章

  • python操作git
    安装模块pip3installgitpython#coding:utf-8importosfromgit.repoimportRepofromgit.repo.funimportis_git_dir#pip3installgitpythonclassGitRepository(object):"""git仓库管理"""def__init__(self,......
  • Python 之生成验证码
    一、代码importrandomfromioimportBytesIOfromPILimportImage,ImageDraw,ImageFont,ImageFilterclassCaptcha:def__init__(self,width,height,code_num=4,code_type=1,font_size=24,is_blur=True,font='Arial.ttf',x_......
  • C++虚函数
    形式:virtual函数类型函数名()(在派生类和基类里都要写)静态成员函数不能是虚函数1.通过指针实现多态对于基类的对象:调用基类的虚函数对于派生类的对象:调用派生类的虚函数#include<iostream>usingnamespacestd;classA{ public: virtualvoidPrint() { cout<<"printA"......
  • Python求100以内的素数常用方法!
    与其他编程语言对比,Python拥有十分独特的优势代码量少,相同功能其他编程语言需要上百行代码才可以实现,而Python只需要十几行就可以实现。而且在Python中,我们只需要学会一些基础的语法就可以实现简单的数值计算,那么Python求100内的所有素数方法是什么?具体内容请看下文。质数......
  • C++知晓某个key值,调用相应的类函数
    1、类函数中定义一个map表typedefint(CClassTest::*pfnMethodExe)(std::stringstrInput,intnInputNum); std::map<std::string,pfnMethodExe>m_fnMethodExecute;CClassTest为类名,typedefint中的int为函数返回值,可以为其他值2、key值和函数对应关系放入map表中m_fnMeth......
  • Python中的时间函数strftime与strptime对比
    一、striftime将给定格式的日期时间对象转换为字符串。日期时间对象=>字符串,控制输出格式.date、datetime、time对象都支持strftime(format) 方法,可用来创建由一个显式格式字符串所控制的表示时间的字符串。用法:datetime.strftime(format)importdatetimedt=datetime.dateti......
  • python+playwright 学习-50 pytest-playwright 多账号操作解决方案
    前言pytest-playwright插件可以让我们快速编写pytest格式的测试用例,它提供了一个内置的page对象,可以直接打开页面操作。但是有时候我们需要2个账号是操作业务流程,比如A账号创建了一个任务,需要用到B账号去操作审批动作等。如果需要2个账号同时登录,可以使用context上下文,它可......
  • Python源码笔记——Python中的列表对象
    1.列表结构体#definePyObject_VAR_HEADPyVarObjectob_base;typedefstruct{PyObjectob_base;Py_ssize_tob_size;/*Numberofitemsinvariablepart*/}PyVarObject;typedefstruct{PyObject_VAR_HEAD/*Vectorofpointerstolistel......
  • Python源码笔记——Python对象机制的基石【PyObject】
    所有源码均基于Python3.11.21.PyObject定义//实际上没有任何东西被声明为PyObject,但是每个指向Python对象的指针都可以转换为PyObject*。//这是手动模拟的继承。同样的,每个指向可变大小的Python对象的指针也可以转换为PyObject*,此外,也可以转换为PyVarObject*。typedefst......
  • Python源码笔记——Python中的整数对象
    1.整数对象在Python3.11.2中,整数结构体叫做PyLongObject。#ifPYLONG_BITS_IN_DIGIT==30typedefuint32_tdigit;...#elifPYLONG_BITS_IN_DIGIT==15typedefunsignedshortdigit;...#else#error"PYLONG_BITS_IN_DIGITshouldbe15or30"#endiftypedefstruc......