10天读完《编写高质量代码 改善Python编程的91个建议》——Day3

计划

Hello,这是一个读书摘要的计划,10天读完《编写高质量代码 改善Python编程的91个建议》,我会每天摘录大概9个书中提到的建议,分享在这里,也作为自己的打卡任务。关于这本书,他并不是python入门的教学书籍,而是一本用来改善编程习惯和风格的书,可以帮助我们写出漂亮的,也就是符合pythonic的python代码。书中的知识难度不会很大,每天看几条,然后落实到实际编程中加以巩固,就能融会贯通,久而久之也就能养成好的编程习惯。如果你没有时间看原书,那么直接看我的摘要就好啦,遇到感兴趣的再去详细了解也会方便很多,当然这里摘要的内容是我觉得有用的部分啦。注意,一定要会运用!

书摘

建议20 优先使用absolute import导入模块

『绝对引入是指import时,都是从sys.path指定的目录下查找包或模块。如:import foo,from foo import bar。有了绝对引入,那要引入同目录下的模块,需要加上.符号,这叫相对引入(relative import, 相对于当前模块来引入)。如:from .foo import bar。而要引入上一层的模块,就用两个点,要引入上上一层就用三个点,如:from ..foo import bar引入上一层的模块。另外,要引入上一层的模块时,不可以写成import ..foo,而是写成from .. import foo。』转自Ovie

建议21 i+=1 不等于 ++i

  1. Python中没有++i操作,会被解释为+(+i),这里的+号表示『正』;同理,-(-i)= i 这里的-表示『负』。

建议22 使用with自动关闭资源

  1. 语法:
with expr1 as e1:
    with expr2 as e2:
        ''''''

建议23 使用else简化循环(异常处理)

1. 实例1 — 打印n以内素数:

# 如果不使用else
def prime(n):
    for i in range(2,n):
        found = True
            for j in range(2,i):
                if i % j == 0:
                    found = False
                    break
        if found:
            print('%d is a prime' % i)

# 使用else,不再需要found来判断
def prime2(n):
    for i in range(2,n):
        for j in range(2,i):
            if i % j == 0:
                break
        else:
            print('%d is a prime' % i)

2. 实例2 — 异常处理

# 如果不使用else
def save(db, obj):
    error_occur = False
    try:
        db.execute('a sql stmt', obj.attr1)
        db.execute('another sql stmt', obj.attr2)
    except DBError:
        db.rollback()
        error_occur = True
    if not error_occur:
        db.commit()

# 使用else,不再需要error_occur来判断
def save(db, obj):
    try:
        db.execute('a sql stmt', obj.attr1)
        db.execute('another sql stmt', obj.attr2)
    except DBError:
        db.rollback()
    else:
        db.commit()

建议24 异常处理的几点基本原则

  1. 注意异常的粒度,try中不要写过多代码
  2. 慎重使用单独except语句处理所有异常
  3. 注意异常捕获的顺序
  4. 使用更为友好的异常信息

建议25 避免finally中可能发生的陷阱

1. finally中使用break,return可能丢失异常
2. try中使用if,else的else前会先执行finally

建议26 深入理解 None,正确判断对象是否为空

  1. None既不是0、False,也不是空字符串,其数据类型为NoneType,是唯一的(所有None都相同)
  2. 判断为空使用『if a』的形式

建议27 连接字符串应有先使用join而不是+

原因:join()方法效率高,尤其是字符串规模较大的时候

建议28 格式化字符串尽量使用.format而不是%

1. %操作

# 直接格式化字符串或者数据
print "the score is %06.1f" % 9.5

# 以元组的形式格式化
print "name: %s; age: %d" % ("Tom", 20)

#以字典的形式格式化
info_dict = {"name": "Tom", "age": 20}
print "name is %s; age is %d." % info_dict

2. .format操作

# 使用位置符号
print "the name is {0}, and the age is {1}.".format("Tom",20)

# 使用名称
print "the name is {name}, and the age is {age}.".format(name="Tom", age=20)

# 通过属性
class Person(object):
    def _init_(self,name,age,gender):
        self.name = name
        self.age = age
        self.gender = gender
    def _str_(self):
        return "Person({self.name},{self.age},{self.gender})".format(self)

str(Person("Tom","20","male"))

# 格式化元组的具体项
point = (2,4)
"X: {0[0]}; Y: {0[1]}".format(point)

3. 为什么 .format 更好?

a)format更灵活
b)format更方便传参
c)%终究被取代(趋势)
d)%有坑,如 "... %s " % ("Tom",) 注意这里必须有逗号

猜你喜欢

转载自www.cnblogs.com/mrdoghead/p/12221695.html