Python中的三重引号

8 投票
3 回答
4378 浏览
提问于 2025-04-18 04:43

我明白如果我这样做

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 个回答

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 的函数。
但是如果你直接从命令行运行这个脚本,三重引号中的测试内容会被执行,并且结果会打印到输出上。

所以,三重引号字符串可以当作字符串的值、注释、文档字符串,也可以用作单元测试的容器。

3

这个字符串只是被计算了一下,解释器发现它没有被赋值给任何东西,就把它丢掉了。

但是在某些特殊的地方,这个字符串实际上被赋值给了这个项目的 __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():
...
12

三重引号 '''""" 是表示字符串的不同方式。使用三重引号的好处是它可以跨多行书写,有时候还可以用作 文档字符串

原因是:

"hadfasdfas"

不会引发错误,因为 Python 只是创建了这个字符串,但没有把它赋值给任何东西。对于 Python 解释器来说,如果你的代码中有一句没什么意义的语句,只要没有语法错误或语义错误,那也是完全可以的。

希望这能帮到你。

撰写回答