gpt4 book ai didi

python - 为什么类和函数不能定义在同一行?

转载 作者:太空宇宙 更新时间:2023-11-04 07:51:26 25 4
gpt4 key购买 nike

出于某种原因,不可能定义这样的方法:

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?')

关于python - 为什么类和函数不能定义在同一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54190472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com