为什么不能在同一行定义 class 和函数?
Why can't a class and function be defined on the same line?
出于某种原因,无法定义这样的方法:
class X:def y():pass #Results in a SyntaxError
但是你可以在同一行定义方法和内容:
def y():print("It works!")
为什么第二个示例有效而第一个示例无效?
对于单行复合语句,正文必须是a simple statement, or a semicolon-separated list of simple statements:
suite ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
statement ::= stmt_list NEWLINE | compound_stmt
stmt_list ::= simple_stmt (";" simple_stmt)* [";"]
不能是复合语句。这将为太多令人困惑和模棱两可的语法打开大门。例如,
if True: if False: pass
else: print('Which "if" does this "else" go with?')
出于某种原因,无法定义这样的方法:
class X:def y():pass #Results in a SyntaxError
但是你可以在同一行定义方法和内容:
def y():print("It works!")
为什么第二个示例有效而第一个示例无效?
对于单行复合语句,正文必须是a simple statement, or a semicolon-separated list of simple statements:
suite ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
statement ::= stmt_list NEWLINE | compound_stmt
stmt_list ::= simple_stmt (";" simple_stmt)* [";"]
不能是复合语句。这将为太多令人困惑和模棱两可的语法打开大门。例如,
if True: if False: pass
else: print('Which "if" does this "else" go with?')