1. 避免finally的陷阱
回顧一下上一節我們畫的圖:
下面看一下這個代碼
def FinallyTest(): print('I am starting------') while True: try: print('I am running') raise IndexError('r') except NameError as e: print('NameError happend {e}'.format(e=e)) break finally: print('finally executed') break # finally語句中有break語句if __name__ == '__main__': FinallyTest()"""output:I am starting------I am runningfinally executed"""
def ReturnTest(a): try: if a <= 0: raise ValueError('data cannot be negtive') else: return a except ValueError as e: print("ValueError:", e) finally: print("The end!") return -1if __name__ == '__main__': print(ReturnTest(0)) print(ReturnTest(2))"""output:ValueError: data cannot be negtiveThe end!-1The end!-1"""
2. None這個東東
# 判斷list是否為空白list = []if list is None: # 錯誤的方式 print("list is None")else: print("list is not None")if list: # 正確的方式 print("list is not None")else: print("list is None")"""output:list is not Nonelist is None"""
3. 連接字串優先使用join而不是+
原因:
str1, str2, str3, str4, str5 = 'my', 'heart', 'will', 'go', 'on'combine_str = ''.join([str1, str2, str3, str4, str5])print(combine_str)"""output:myheartwillgoon"""
4. 用format而不是%
weather = ['a', 'b', 'c']formatter = 'letter is: {0}'.formatfor item in map(formatter, weather): print(item)"""output:letter is: aletter is: bletter is: c"""
5. 區別可變對象和不可變對象
class Student(object): def __init__(self, name, course=[]): # 這裡有一個警告:Default argument value is mutable self.name = name self.course = course # def __init__(self, name, course=None): # 這是對上一個代碼的修改 # self.name = name # if course is None: # self.course = [] # else: # self.course = course def addcourse(self,coursename): self.course.append(coursename) def printcoursename(self): print("student {self.name}'s course are:".format(self=self)) for item in self.course: print(item)LiMing = Student('LiMing')LiMing.addcourse("Math")LiMing.printcoursename()David = Student('David')David.addcourse("Art")David.printcoursename()print(id(LiMing), "|", id(David))print(id(LiMing.name), "|", id(David.name))print(id(LiMing.course), "|", id(David.course))"""output1:student LiMing's course are:Mathstudent David's course are:MathArt2168438350288 | 21684383504562168438237256 | 21684383280402168438334024 | 2168438334024output2:student LiMing's course are:Mathstudent David's course are:Art1946024173976 | 19460241741441946024061000 | 19460241517841946024178760 | 1946024157768"""