Why python docstring is interpreted differently from comment

怎甘沉沦 提交于 2019-12-02 08:06:01

问题


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

def myFunc():
    # useful function to calculate stuff

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

def myFunc():
    # useful function to calculate stuff
    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?


回答1:


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).

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.




回答2:


A comment is outright ignored by the interpreter, so omitting a block after an indent is a syntax error. However, a docstring is a real Python object--at its most basic, a literal str. A lone expression is a valid block of code:

'This is a string. It is a valid (though pretty useless) line of Python code.'

In the case of docstrings in particular, there's also some additional functionality going on, such as being used to set the __doc__ attribute.

>>> def myFunc():
...     '''MyDocString'''
...
>>> print(myFunc.__doc__)
MyDocString

Note that this also works for classes:

>>> class MyClass(object):
...     '''MyClassDocString'''
...
>>> print(MyClass.__doc__)
MyClassDocString


来源:https://stackoverflow.com/questions/21245572/why-python-docstring-is-interpreted-differently-from-comment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!