为什么python docstring的解释与注释不同 [英] Why python docstring is interpreted differently from comment

查看:60
本文介绍了为什么python docstring的解释与注释不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个这样的函数:

Let's say, I've got a function like this:

def myFunc():
    # useful function to calculate stuff

这会产生一个缩进错误,除非我添加pass:

This will produce an indentation error, unless I add pass:

def myFunc():
    # useful function to calculate stuff
    pass

但是,如果我用 docstring 替换注释,则不需要 pass:

However, if I replace a comment with docstring, no pass is necessary:

def myFunc():
    """useful function to calculate stuff"""

这似乎是一个奇怪的功能,因为据我所知,这两个功能都没有在程序中使用.那么,它为什么会这样呢?

This seems like an odd feature as neither of these are used in the program, as far as I know. So, why does it behave like this?

推荐答案

文档字符串不是只是一个注释.它实际上对解释器有意义.在使用文档字符串的情况下,您可以执行 myFunc.__doc__ 并实际取回您的文档字符串(在另一种情况下使用 pass,结果 myFunc.__doc__ 将是 None).

A docstring isn't just a comment. It actually has meaning to the interpreter. In the case with a docstring, you could do myFunc.__doc__ and actually get your docstring back (In the other case with a pass, the result myFunc.__doc__ would be None).

换句话说,您实际上是在函数体中添加一些代码来修改它的行为(在某些情况下),因此不需要 pass.

In other words, you are actually adding some code to the function body to modify it's behavior (in some circumstances), so no pass is necessary.

这篇关于为什么python docstring的解释与注释不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆