python 从函数名看完整定义

python see the full definition from the name of the function

我最近问了一个标题为 "python find the type of a function" 的问题,得到了非常有帮助的答案。这是一个相关的问题。

假设我导入了我编写的 *.py 文件,这些导入导致 f 成为我定义的函数之一。现在我写信给我的 python 翻译 x = f。后面想看f的完整定义,最好还有注释,只知道x。这可能吗? python 是否记得定义是从哪个文件导入的,这当然不足以给出 f 的完整定义,除非能找到实际的相关定义?

内置 help(object) 将为您提供正确的文档,如果您将 k 作为您评论的某些函数的别名 - inspect.getsource(k) 也是如此 - 他们 知道 此时你的变量名别名k是哪个函数

参见:


示例:

# reusing this code - created it for some other question today

class well_documented_example_class(object):
    """Totally well documented class"""

    def parse(self, message):
        """This method does coool things with your 'message'

        'message' : a string with text in it to be parsed"""
        self.data = [x.strip() for x in message.split(' ')]
        return self.data


# alias for `parse()`:        
k = well_documented_example_class.parse
help(k)

打印:

Help on function parse in module __main__:

parse(self, message)
    This method does coool things with your 'message'

    'message' : a string with text in it to be parsed

inspect.getsource(k)也是如此:

# from 
import inspect
print(inspect.getsource(k))

打印:

def parse(self, message):
    """This method does coool things with your 'message'

    'message' : a string with text in it to be parsed"""
    self.data = [x.strip() for x in message.split(' ')]
    return self.data

你应该想到Python使用变量的方式。您有 objects(可以是 类、函数、列表、标量或其他)和仅包含对这些对象的引用的 variables

这就解释了为什么当多个变量指向同一个可变对象时,如果您通过其中一个变量更改它,则更改在所有其他变量中都是可见的。

这里也是一样的。函数对象管理它的所有属性:它的文档字符串、它的代码和它的源代码(如果它有:C function show no source)。将函数分配给新变量不会隐藏对象:您仍然可以访问原始对象。

装饰器的情况会有所不同,因为装饰器会创建一个新对象,而原始对象仅对装饰器可用。