代码改变世界

python相关小技巧整理[持续更新]

2016-07-22 16:13  chercher  阅读(193)  评论(0编辑  收藏  举报

1. pdb的非常方便的debug,抛弃print吧~ 参考https://www.ibm.com/developerworks/cn/linux/l-cn-pythondebugger/

import pdb; pdb.set_trace() 来设置一个断点,在你出错的位置之前,之后可以参考链接中的操作,一步步p来print,n来执行next的方法~

 

2. python logging  参考 http://python.jobbole.com/81666/

 

3. self 与 cls 的写法用

(找到的一些简单直接的解释)

只是python中约定的写法,本质上只是一个函数参数而已,没有特别含义。

任何对象调用方法都会把把自己作为该方法中的第一个参数,传递到函数中。(因为在python中万物都是对象,所以当我们使用Class.method()的时候,实际上的第一个参数是我们约定的cls)

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

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.

 

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

              最大值是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