python中的三重引用

时间:2014-04-29 09:48:20

标签: python syntax

所以我明白,如果我做以下

print """ Anything I 
          type in here 
          works. Multiple LINES woohoo!"""

但是,如果以下是我的python脚本

""" This is my python Script. Just this much """

上述事情是做什么的?它被视为评论吗?为什么不是语法错误?

同样,如果我这样做

"This is my Python Script. Just this. Even with single quotes."

如何解释上述两个脚本?

由于

3 个答案:

答案 0 :(得分:11)

三重引号'''"""只是表示字符串的不同方式。三重引号的优点是它可以跨越多行,有时可以作为docstrings

原因:

"hadfasdfas"

不会引发任何错误,因为python只是创建字符串,然后不将其分配给任何东西。对于python解释器,只要没有语法或语义错误,如果你的代码中有一个无意义的语句就完全没问题了

希望有所帮助。

答案 1 :(得分:2)

该字符串刚被评估,并且解释器注意到它没有被分配给任何东西,将其抛弃。

但在某些特殊地方,此字符串实际上已分配给该项目的__doc__属性:

def func(arg):
  """
  Does stuff. This string will be evaluated and assigned to func.__doc__.
  """
  pass

class Test:
  """
  Same for Test.__doc__
  """
  pass

位于module.py的顶部:

"""
module does stuff. this will be assigned to module.__doc__
"""
def func():
...

答案 2 :(得分:1)

除了@ sshashank124答案之外,我还要补充说,三重引用的字符串也用于测试https://docs.python.org/2/library/doctest.html

请考虑以下代码段:

def some_function(x, y):
"""This function should simply return sum of arguments.
It should throw an error if you pass string as argument

>>> some_function(5, 4)
9
>>> some_function(-5, 4)
-1
>>> some_function("abc", 4)
Traceback (most recent call last):
    ...
ValueError: arguments must numbers
"""
if type(x, str) or type(y, str):
    raise ValueError("arguments must numbers")
else:
    return x + y

if __name__ == "__main__":
    import doctest
    doctest.testmod()

如果您导入这个小模块,您将获得some_function功能 但是如果直接从shell调用此脚本,将评估三重引用字符串中给出的测试,并将报告打印到输出中。

因此,三重引用的字符串可以被视为string类型的值,注释,docstrings和unittests的容器。