2013-07-18 10 views
18
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 

, iş arkadaşı sordu:Neden python bir "pass" ifadesi olmayan boş bir işleve (doc-string ile) izin verir? Yukarıdaki benzer bazı kod Yeni bir gözden

Nasıl method_one başarıyla ayrıştırılıp piton tarafından kabul edilen geldin? Boş bir işlev sadece pass'dan oluşan bir gövdeye ihtiyaç duymuyor mu? yani böyle görünmemeli mi?

anda Benim yanıt olarak
def method_one(self): 
    """This is the first method, will do something useful one day""" 
    pass 

gibi bir şey: docstring'ini genellikle "infaz" olmadığı için, fonksiyon gövdesinin bir parçası olarak kabul edilmez

rağmen, ayrıştırılır bu nedenle, pass ihmal edilebilir. sharing knowledge Q&A style ruhuyla

, ben burada daha titiz yanıt sonrası düşündüm.

cevap

17

ayrıştırıcı jeneratör tarafından okunan ve Python kaynak dosyalarını ayrıştırmak için kullanılan Python 2.7.5 grammar specification göre, bir fonksiyon şöyle görünür:

funcdef: 'def' NAME parameters ':' suite 

fonksiyon gövdesi bu

gibi görünen bir suite olduğunu
suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT 

dilbilgisi aracılığıyla bu tüm yol ardından, stmt sadece tekolabilir sadece testlist olabilecek bir expr_stmt, olabilir 10 (eninde sonunda) sadece bir STRING olan bir atom olabilir. Docstring. dilbilgisi şartname O_O okumak zordur

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+) 
+2

o: İşte

aracılığıyla takip etmek doğru sırayla, dilbilgisi sadece uygun parçalardır –