gpt4 book ai didi

python - 为什么 python 允许没有 "pass"语句的空函数(带有文档字符串)主体?

转载 作者:IT老高 更新时间:2023-10-28 20:41:34 26 4
gpt4 key购买 nike

class SomeThing(object):
"""Represents something"""

def method_one(self):
"""This is the first method, will do something useful one day"""

def method_two(self, a, b):
"""Returns the sum of a and b"""
return a + b

最近在复习一些类似上面的代码时,一位同事问道:

How come method_one is successfully parsed and accepted by python? Doesn't an empty function need a body consisting of just pass? i.e. shouldn't it look like this?

def method_one(self):
"""This is the first method, will do something useful one day"""
pass

我当时的 react 是这样的:

Although the docstring is usually not considered to be part of the function body, because it is not "executed", it is parsed as such, so the pass can be omitted.

本着 sharing knowledge Q&A style 的精神,我想我会在这里发布更严格的答案。

最佳答案

根据Python 2.7.5 grammar specification ,由解析器生成器读取并用于解析Python源文件,函数如下所示:

funcdef: 'def' NAME parameters ':' suite

函数体是一个套件,看起来像这样

suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT

顺着这个语法,stmt可以是expr_stmt,也可以是teSTList,也可以是teSTList单个 test 可以(最终)只是一个 atom,也可以只是一个 STRING。文档字符串。

这里只是语法的适当部分,按照正确的顺序进行:

stmt: simple_stmt | compound_stmt
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
small_stmt: (expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
import_stmt | global_stmt | exec_stmt | assert_stmt)
expr_stmt: testlist (augassign (yield_expr|testlist) |
('=' (yield_expr|testlist))*)
testlist: test (',' test)* [',']
test: or_test ['if' or_test 'else' test] | lambdef
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)*
comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
expr: xor_expr ('|' xor_expr)*
xor_expr: and_expr ('^' and_expr)*
and_expr: shift_expr ('&' shift_expr)*
shift_expr: arith_expr (('<<'|'>>') arith_expr)*
arith_expr: term (('+'|'-') term)*
term: factor (('*'|'/'|'%'|'//') factor)*
factor: ('+'|'-'|'~') factor | power
power: atom trailer* ['**' factor]
atom: ('(' [yield_expr|testlist_comp] ')' |
'[' [listmaker] ']' |
'{' [dictorsetmaker] '}' |
'`' testlist1 '`' |
NAME | NUMBER | STRING+)

关于python - 为什么 python 允许没有 "pass"语句的空函数(带有文档字符串)主体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17735170/

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