1. 若sequences (strings, lists, tuples) 為空, 則當 False. 和true / false 比較用 is / is not
2. Comparisons to singletons like None should always be done with is or is not,
never the equality operators (
Example from stackoverflow)
3. 愛用 in 跟 string.find()
4. Tuple 除了 packing / Unpacking, 在做 swap 時不用暫時變數, 且可以 return multi-values
4.1
C program to swap two numbers
5. Python 沒有 ternary operator
?:
5.1 推薦的
conditional expressions 寫法
6. 善用 enumerate (
Example from seanlin's blog)
7. loop with else (
Example from python tutorial)
Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.
8. Chained comparisons (if a < b < c <= d)
9. Default argument values (It's warning to use mutable as default values)
The default values are evaluated at the point of function definition ins the defining scope :
i = 5
def f(arg=i):
print arg
i = 6
f()
Will print 5.
def f(a, L=[]):
L.append(a)
return L
print f(1)
print f(2)
print f(3)
Will print :
[1]
[1, 2]
[1, 2, 3]
If you don't want the default to be shard between subsequent calls :
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
10. 用 join 來串接 list ()
11. 用 property 取代 getters, setters (
From seanlin's blog)
class Egg(object):
def __init__(self, price):
self._price = price
@property
def price(self):
return self._price * RATE
@price.setter
def price(self, value):
self._price = value
12. Context managers (
From seanlin's blog)