improve your python code(7)__python

來源:互聯網
上載者:User
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"""

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.