Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中的三重引号_Python_Syntax - Fatal编程技术网

python中的三重引号

python中的三重引号,python,syntax,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. Ev

所以我明白如果我做了以下事情

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."
如何解释上述两个脚本

谢谢

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

原因是:

“hadfasfas”

不会引发任何错误是因为python只是创建字符串,然后不将其分配给任何对象。对于python解释器,只要代码中没有语法或语义错误,就可以使用无意义的语句


希望这能有所帮助。

字符串刚刚被计算过,而解释器发现它没有被分配到任何东西,就把它扔掉了

但在某些特殊位置,此字符串实际上被分配给项目的
\uuuu doc\uuu
属性:

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

class Test:
  """
  Same for Test.__doc__
  """
  pass
模块.py的顶部

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

除了@sshashank124 answer之外,我必须补充一点,在测试中还使用了三重引号字符串

请考虑此代码片段:

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\u函数
函数。
但是,如果直接从shell调用此脚本,则将对三重引号字符串中给出的测试进行评估,并将报告打印到输出中


因此,三重引号字符串可以被视为字符串类型的值、注释、文档字符串和单元测试的容器。

是的,我错过了。谢谢,我不明白,所以当我运行此脚本时会发生什么。首先,我不确定x和y的值是什么?请详细说明。谢谢,如果您将其保存为带有ext的文件类似于
某个模块.py
它会变成一个模块。如果你导入它,那么
\uuu name\uuuuu==“\uuuu main\uuuuu”
False
所以没有什么神奇的事情发生。但是如果你从shell调用它,例如
python某个模块.py
最后两行就会被执行。在这种情况下
doctestmod.test()
将扫描docstring以查找Python单元测试。因此它会找到
>
,这意味着执行
在我的代码片段中,第一个单元测试调用
一些函数(5,4)
。此调用的预期结果放在下一行。有时会像第三个单元测试一样出现异常。如果结果如预期的那样,测试就会成功。