Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.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_Python 3.x_Language Lawyer - Fatal编程技术网

python为什么使用';断言测试';而不是';断言(测试)';?

python为什么使用';断言测试';而不是';断言(测试)';?,python,python-3.x,language-lawyer,Python,Python 3.x,Language Lawyer,在python2中,可以使用print 123和print(123),以及assert True和assert(True) 在python3中,为什么我不能使用print 123,而能够使用assert True?简短回答:assert不是一个函数 长答覆: 当python3问世时,它改变(或删除)了print sth语法,因为print变成了一个内置的函数,所以它应该被称为 虽然assert可以像函数一样使用(assert(True)),但它不是函数-它实际上是中的语法,就像python2中的

在python2中,可以使用
print 123
print(123)
,以及
assert True
assert(True)


在python3中,为什么我不能使用
print 123
,而能够使用
assert True

简短回答:
assert
不是一个函数

长答覆:

当python3问世时,它改变(或删除)了
print sth
语法,因为
print
变成了一个内置的函数,所以它应该被称为

虽然
assert
可以像函数一样使用(
assert(True)
),但它不是函数-它实际上是中的语法,就像python2中的print一样

与执行
type(print)
时类型为
class'builtin\u function\u或\u method'
print
不同,当您尝试
type(assert)
type(if)
时,您将得到以下结果:

SyntaxError: invalid syntax

因此,在使用
assert True
时不能使用
print 123
,因为这两者是不同的。

在Python 2中,
print
assert
都是语句(如
if
while
def
等)。在这种情况下,paren不被解释为函数调用操作符,而是被解释为普通paren,强制对其内容进行评估,在这种情况下,这是一个no-op,实际上被认为是非音阶的

在Python3中,
print()
成为一个函数,因此必须调用它
assert
仍然是一条语句,因此它的工作原理与Python 2中的一样