python相關小技巧整理[持續更新]

1. pdb的很是方便的debug,拋棄print吧~ 參考https://www.ibm.com/developerworks/cn/linux/l-cn-pythondebugger/python

import pdb; pdb.set_trace() 來設置一個斷點,在你出錯的位置以前,以後能夠參考連接中的操做,一步步p來print,n來執行next的方法~linux

 

2. python logging  參考 http://python.jobbole.com/81666/函數

 

3. self 與 cls 的寫法用spa

(找到的一些簡單直接的解釋)debug

只是python中約定的寫法,本質上只是一個函數參數而已,沒有特別含義。code

任何對象調用方法都會把把本身做爲該方法中的第一個參數,傳遞到函數中。(由於在python中萬物都是對象,因此當咱們使用Class.method()的時候,實際上的第一個參數是咱們約定的cls)對象

self is used in instance methods, cls is often used in class methodsblog

When a method is decorated with @classmethod it gets the class passed as its first argument so the most common name for it is cls as it points to the class.ip

 

4. python最小值是-sys.maxint - 1ci

              最大值是sys.maxint+1

 

5. python -m tabnanny qaci_script.py  能夠看tab和space的問題

 

6. u'() 來解決decode 的問題

 

7. DocString

形式爲'''第一行爲標題 中間空一行 下面是解釋'''

能夠用object.__doc__ 的方式調用,能夠使程序更加簡單易懂

 

 8. 字符串鏈接的寫法

s = ''

for i in seq:

    s += chr(i) 

 這種寫法很差,而比較好的是用join

''.join(chr(i) for i in seq)

 

9. list是可變對象,改變list的函數一般沒有返回值

eg. a = []

     a.sort() 沒有返回值

可是能夠用 sorted(a)

 

10.mutable: list, dict, set, 類實例    immutable: 數值類型, 字符串, tuple 

 

11. Collection 模塊,還沒填完坑

 

12. if.. else 的用法

anwser = "yes!" if rank == 1 else "no"

 

13. 強大zip!

i = ('a', 'b', 'c')

j = (1, 2, 3)

for m, n in zip(i, j):

    print i,j

# the result is
# a 1
# b 2
# c 3

 

14. args:set   kwargs:dict

相關文章
相關標籤/搜索