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
if __name__ ==
'__main__':
FinallyTest()
"""output:
I am starting------
I am running
finally 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 -
1
if __name__ ==
'__main__':
print(ReturnTest(
0))
print(ReturnTest(
2))
"""output:
ValueError: data cannot be negtive
The end!
-1
The end!
-1
"""
2. None这个东东
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 None
list 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
"""
weather = [
'a',
'b',
'c']
formatter =
'letter is: {0}'.format
for item
in map(formatter, weather):
print(item)
"""
output:
letter is: a
letter is: b
letter is: c
"""
5. 区别可变对象和不可变对象
class Student(object):
def __init__(self, name, course=[]):
self.name = name
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:
Math
student David's course are:
Math
Art
2168438350288 | 2168438350456
2168438237256 | 2168438328040
2168438334024 | 2168438334024
output2:
student LiMing's course are:
Math
student David's course are:
Art
1946024173976 | 1946024174144
1946024061000 | 1946024151784
1946024178760 | 1946024157768
"""