Why python docstring is interpreted differently from comment

前端 未结 2 1981
北海茫月
北海茫月 2021-01-23 16:56

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

def myFunc():
    # useful function to calculate stuff

This will produce an indentation error, unle

2条回答
  •  温柔的废话
    2021-01-23 17:13

    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
    

提交回复
热议问题