获取Python函数信息的方法

yizhihongxing

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

原文链接:https://www.cnblogs.com/python1111/p/17296568.html

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:获取Python函数信息的方法 - Python技术站

(0)
上一篇 2023年4月18日
下一篇 2023年4月18日

相关文章

  • python列表与元组详解实例

    以下是“Python列表与元组详解实例”的完整攻略。 1. 列表和元组的概述 列表和元组都是Python中常用的结构。它们都可以用于存储多元素,但它们之间有些重要的区别。列表是可变的,可以添加、删除和修改元素,而元组是不可变的,一旦创建就不能修改。 2. 列表的实现 2.1 创建列表 我们可以使用方括号[]来创建一个空列表,或者在括号中添加元素来创建一个非空…

    python 2023年5月13日
    00
  • 详解Python 类的__repr__方法转换字符串

    __repr__是Python类中的魔术方法之一,用于定义对象的字符串表示形式。该方法被调用时不需要显式地调用它,而是在使用repr()函数或交互式解释器显示变量时自动调用。其主要目的是为了方便人们查看对象的状态,以便在调试时使用。 下面我们来详细讲解Python类的__repr__方法转换字符串的使用方法。 定义__repr__方法 我们首先要在类的定义中…

    python-answer 2023年3月25日
    00
  • python中setuptools的作用是什么

    Python中的setuptools是一种用于管理Python软件项目的工具包。它包括命令行工具和Python库,并提供了一个统一的接口来发现、安装、构建和发布Python模块和包。 setuptools的主要作用包括: 管理Python依赖项。 setuptools允许您指定项目所依赖的Python软件包及其版本信息,以便在安装Python软件包时确保所有…

    python 2023年6月3日
    00
  • 解决python3安装pandas出错的问题

    解决Python3安装pandas出错的问题 在Python3中,安装pandas是非常常见的操作。但是,在安装pandas时,有时会出现安装的情况。本文将详细讲解解决Python3安装p出错的问题,包括安装依赖库、使用pip安装p等。在过程中,提供两个示例说明,帮助读者好地理解pandas安装的注意事项。 安装依库 在Python3中,安装pandas之前…

    python 2023年5月13日
    00
  • Python for循环生成列表的实例

    Python for循环生成列表的实例 在Python中,我们可以使用for循环来生成列表。这种方法可以让我们更加灵活地控制列表的生成过程,而满足不同的需求。本攻略将详细介绍如何使用for循环生成列表,并提供两个例说明。 生成列表 我们可以使用for循环生成数字列表。以下是一个示例代码,演示如何使用for循环生成数字列表: # 生成列表 my_list = …

    python 2023年5月13日
    00
  • Pycharm IDE的安装和使用教程详解

    Pycharm IDE的安装和使用教程详解 Pycharm是什么? Pycharm是一款Python集成开发环境,提供了丰富的开发功能和调试工具,广泛使用于Python开发者中。Pycharm支持Python 2和Python 3版本,并提供了许多插件和第三方工具支持。 安装Pycharm 下载Pycharm安装包 Pycharm官网地址为:https://…

    python 2023年5月19日
    00
  • Django笔记二十三之case、when操作条件表达式搜索、更新等操作

    本文首发于公众号:Hunter后端原文链接:Django笔记二十三之条件表达式搜索、更新等操作 这一篇笔记将介绍条件表达式,就是如何在 model 的使用中根据不同的条件筛选数据返回。 这个操作类似于数据库中 if elif else 的逻辑。 以下是本篇笔记的目录: model 和数据准备 When 和 Case 操作新增字段返回 条件搜索 条件更新 条件…

    python 2023年4月17日
    00
  • Python 标准库zipfile将文件夹加入压缩包的操作方法

    当我们想要将一个文件夹加入到 zip 压缩包中时,可以使用 Python 标准库 zipfile 提供的方法来实现。下面是详细的操作流程: 导入 zipfile 库 import zipfile 实例化 ZipFile 对象 # file_name 是压缩包的路径和名称,可以自己定义 my_zipfile = zipfile.ZipFile(file_nam…

    python 2023年6月3日
    00
合作推广
合作推广
分享本页
返回顶部