improve your python code(7)

来源:互联网 发布:苹果mac回收 编辑:程序博客网 时间:2024/05/18 22:13

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"""

这里写图片描述

这里写图片描述

1 0