python - python 从函数名看完整定义
问题描述
我最近问了一个标题为“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 https://stackoverflow.com/a/52333691/7505395
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
推荐阅读
- javascript - LitElement:从属性设置样式
- java - Apache Camel 可以处理的最大路由数
- css - 整个 Ionic 的背景图像(4)页面不重叠页眉和页脚
- javascript - 将对象推送到 Jquery 中的数组中
- sql - 雪花中的排序规则
- python - 如何使静态的、本地可访问的 html 表可排序?
- python - Pandas - 在列列表中用零标识行
- javascript - Google Maps 侦听器在 `d3.csv()` 中不起作用
- android - 无法将firebase添加到android(颤振)
- node.js - 有没有办法运行一个可以将变量传递给下一个的自终止 js 脚本?