这不仅仅是一个编码风格的问题.如果您了解python(我认为Ruby也有类似的东西),您可以在函数中使用docstring,这样您就可以通过发出"help"命令轻松获取该字符串.例如:
def something(t=None):
'''Do something, perhaps to t
t : a thing
You may not want to do this
'''
if t is not None:
return t ** 2
else:
return 'Or maybe not'
Run Code Online (Sandbox Code Playgroud)
然后help(something)返回以下内容:
Help on function something in module __main__:
something(t=None)
Do something, perhaps to t
t : a thing
You may not want to do this
Run Code Online (Sandbox Code Playgroud)
R中的工作方式,你可以获得定义的代码片段的全文,这样你就可以看到注释(包括函数开头的注释),但这可能是很多滚动和可视化过滤.有没有更好的方法?
Das*_*son 13
我最近写了一个包来做这个任务.该文档字符串包可以写出自己的,因为它们是记录功能中roxygen风格注释文档.例如,人们可以这样做
square <- function(x){
#' Square a number
return(x^2)
}
Run Code Online (Sandbox Code Playgroud)
然后查看文档要么调用docstring函数
docstring(square)
Run Code Online (Sandbox Code Playgroud)
或使用内置的?支持和做
?square
Run Code Online (Sandbox Code Playgroud)
注释可以是上面显示的单个块,也可以是完全roxygen样式,以利用提供的一些关键字
square <- function(x){
#' Square a number
#'
#' Calculates the square of the input
#'
#' @param x the input to be squared
return(x^2)
}
Run Code Online (Sandbox Code Playgroud)
这是在CRAN上:https://cran.r-project.org/package=docstring 所以你可以使用
install.packages("docstring")
Run Code Online (Sandbox Code Playgroud)
或者如果你想要最新的开发版本,你可以从github安装:
library(devtools)
install_github("dasonk/docstring")
Run Code Online (Sandbox Code Playgroud)
chl*_*chl 11
您可以将任何attributes您喜欢的内容添加到R对象中,包括函数.所以像
describe <- function(obj) attr(obj, "help")
foo <- function(t=NULL) ifelse(!is.null(t), t^2, "Or maybe not")
attr(foo, "help") <- "Here is the help message"
Run Code Online (Sandbox Code Playgroud)
产生或多或少的期望输出
> foo(2)
[1] 4
> foo()
[1] "Or maybe not"
> describe(foo)
[1] "Here is the help message"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5356 次 |
| 最近记录: |