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
- improve your python code(7)
- improve your python code(1)
- improve your python code(2)
- improve your python code(3)
- improve your python code(4)
- improve your python code(5)
- improve your python code(6)
- improve your python code(8)
- improve your python code(9)
- improve your python code(10)
- improve your python code(11)
- improve your python code(12)
- improve your python code(13)
- Improve Your Python: 'yield' and Generators Explained
- Improve Your Python: 'yield' and Generators Explained
- How to improve quality and syntax of your Android code
- Teaching course1 : How to improve your code quality
- 转-Code-Switching-to-Improve-Your-Writing-and-Productivity
- 这些年坚持写博客,我得到了什么
- 数据结构---线索二叉树
- Java BigDecimal详解
- %matplotlib inline syntax error
- MongoDB——shutting down with code:100
- improve your python code(7)
- linux 更改组名称
- 数据结构学习-堆栈
- 移动端页面开发相关知识
- python-cookbook学习笔记十 迭代器 三
- vue的开始:脚手架vue-cli的安装
- 用SQL语句查询数据库中某一字段下相同值的记录方法
- IOS 二维码
- 关于树莓派