所以我偶然发现了Python language (https://docs.python.org/3/reference/grammar.html)的语法,我不能完全理解它是如何工作的。特别是,我对这段关于if语句的片段很感兴趣。
if_stmt: 'if' namedexpr_test ':' suite ('elif' namedexpr_test ':' suite)* ['else' ':' suite]
[...]
namedexpr_test: test [':=' test]
test: or_test ['if' or_test 'else' test] | lambdef
test_nocond: or_test | lambdef_nocond
lambdef: 'lambda' [varargslist] ':' test
lambdef_nocond: 'lambda' [varargslist] ':' test_nocond
or_test: and_test ('or' and_test)*
and_test: not_test ('and' not_test)*
not_test: 'not' not_test | comparison
comparison: expr (comp_op expr)*
# <> isn't actually a valid comparison operator in Python. It's here for the
# sake of a __future__ import described in PEP 401 (which really works :-)
comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'这里有一定的风格。用and_test定义or_test,再用not_test定义and_test。这种风格的优点是什么?(因为我看到它在C++的语法中也用到了,很可能很多其他语言也用到了)。
发布于 2020-04-20 19:56:49
它对优先级进行编码。使用此语法,您可以明确地解析表达式
not x and y or z作为
or_test
/ \
/ z
and_test
/ \
/ y
not_test
|
x以“预期”的方式,不需要括号。
https://stackoverflow.com/questions/61321667
复制相似问题