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
最近在回顾一些与上面类似的代码时,一位同事问道:
怎么会method_one
python 是否成功解析并接受?空函数不需要一个由以下内容组成的函数体吗pass http://docs.python.org/2/reference/simple_stmts.html#pass?即它不应该看起来像这样吗?
def method_one(self):
"""This is the first method, will do something useful one day"""
pass
我当时的反应是这样的:
虽然文档字符串通常不被认为是函数体的一部分,但因为它没有“执行”,所以它被解析为这样,所以pass
可以省略。
本着分享知识问答方式 https://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/,我想我应该在这里发布更严格的答案。
根据Python 2.7.5 语法规范 http://docs.python.org/2/reference/grammar.html,由解析器生成器读取并用于解析Python源文件,函数如下所示:
funcdef: 'def' NAME parameters ':' suite
函数体是一个suite
看起来像这样
suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
遵循这个语法,stmt
可以是一个expr_stmt
,这可以只是一个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+)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)