2016-05-12 20 views
1

是否可以查看方法的工作方式?例如列表方法count()。 我有一個列表:任何方法的Python細節

li = [3, 5, 6, 7, 3, 3, 3] 

當我鍵入

print li.count(3) 

的ouptut將4.我如何能看到這個魔術發生代碼? 命令幫助(list.count)給出的短信息不足:

>>> help(list.count) 
Help on method_descriptor: 

count(...) 
    L.count(value) -> integer -- return number of occurrences of value 
+1

'help(list.count)',請閱讀[文檔](https://docs.python.org/2/tutorial/datastructures.html#more-on-lists)或看[source]( https://github.com/python/cpython/blob/master/Objects/listobject.c#L2173)。 –

+0

您是否試過Google搜索Python的源代碼? – TigerhawkT3

+0

是的,我試圖在Google中找到這段代碼。但我沒有成功。 – goodgrief

回答

1

大多數內建在C語言實現的,所以你將無法看到的代碼。然而,您可以通過「幫助」功能獲得詳細的幫助。

help(li.count) 

這給了你足夠的信息來真的知道你可以用任何物體你提供到幫助做些什麼事情。當我開始時我所做的就是編寫我自己的模擬功能的函數。這使你能夠很好地掌握所有你需要考慮的事情。 這裏的計數功能如何能看起來像一個例子:

def count(crit, iterable): 
    i = 0 
    for item in iterable: 
     if crit == item: 
      i += 1 
    return i 

作爲替代,很多東西(如Tkinter的模塊)是用Python編寫的,你可以看看他們在pythonx.x/Lib/tkinter(用你想看的任何模塊替換tkinter)。 我希望能夠很好地回答你的問題。