improve your python code(7)

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 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是否为空
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
"""

这里写图片描述

4. 用format而不是%

这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

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=[]):  # 这里有一个警告: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:
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
"""

这里写图片描述

这里写图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值