Skip to main content
 首页 » 编程设计

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

2025年05月04日13grandyang

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

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