python怎么查看函数源代码

  • Post category:Python

想要查看Python函数源代码,有以下几种方法:

方法一: 使用内置的type()函数

type()函数可以用来查询一个对象的类型,并且可以获取这个对象的__doc__或者__docstring__属性。我们可以通过打印这个属性来获取函数的源代码。下面是一个示例:

import math

# 打印math模块中的cos函数源代码
print(math.cos.__doc__)

在运行以上代码后,可以看到输出结果为:

Return the cosine of x (measured in radians).

The cosine function relates the legs of a right triangle to the hypotenuse.
===================
在 Python 3.x 中,使用 __doc__ 等同于使用 __doc__ 等价与使用 __doc__ 等价于 help()

上述代码中,我们首先用了import语句引入了math模块。之后,我们使用两个下划线“__”加上doc或者 docstring属性获取了math模块中cos函数的源代码并进行打印。

方法二: 使用inspect模块

Python的inspect模块是专门用来操作各类对象的模块,通过它可以获取到对象的很多信息,如函数定义、函数传入的参数类型等。它的signature()方法可以用于获取函数的参数信息。下面是一个示例:

import inspect

# 自定义一个函数
def my_func(name, age):
    '''
    返回一个字符串:name is age years old.
    '''
    return '{} is {} years old.'.format(name, age)

# 打印 my_func 的定义
print(inspect.getsource(my_func))

在运行以上代码后,可以看到输出结果为:

自定义一个函数

    :return: 返回一个字符串:name is age years old.

def my_func(name, age):
    '''
    返回一个字符串:name is age years old.
    '''
    return '{} is {} years old.'.format(name, age)

上述代码中,我们定义了一个my_func函数,之后使用了inspect.getsource()方法获取了函数的源代码,并进行打印输出。

注意:如果要使用 inspect.getsource() 方法获取到函数的源代码,必须要将函数定义写在request范围内,否则将会出现报错。