可读性很重要

Python 中的软件工程原理

Adam Spannbauer

Machine Learning Engineer

Python 之禅

import this
《Python之禅》,作者 Tim Peters(节选)

美胜于丑。
显式优于隐式。
简单优于复杂。
复杂优于繁琐。
可读性很重要。
若实现难以解释,则不是好主意。
若实现易于解释,可能是好主意。
Python 中的软件工程原理

描述性命名

命名不佳

def check(x, y=100):
    return x >= y

描述性命名

def is_boiling(temp, boiling_point=100):
    return temp >= boiling_point

过度命名

def check_if_temperature_is_above_boiling_point(
        temperature_to_check, 
        celsius_water_boiling_point=100):
    return temperature_to_check >= celsius_water_boiling_point
Python 中的软件工程原理

保持简单

《Python之禅》,作者 Tim Peters(节选)

简单优于复杂。
复杂优于繁琐。

  披萨切片

Python 中的软件工程原理

做披萨——复杂版

def make_pizza(ingredients):
    # Make dough
    dough = mix(ingredients['yeast'],
                ingredients['flour'],
                ingredients['water'],
                ingredients['salt'],
                ingredients['shortening'])

    kneaded_dough = knead(dough)
    risen_dough = prove(kneaded_dough)

    # Make sauce
    sauce_base = sautee(ingredients['onion'],
                                ingredients['garlic'],
                                ingredients['olive oil'])

    sauce_mixture = combine(sauce_base,
                            ingredients['tomato_paste'],
                            ingredients['water'],
                            ingredients['spices'])

    sauce = simmer(sauce_mixture)
    ...
Python 中的软件工程原理

做披萨——简化版

def make_pizza(ingredients):
    dough = make_dough(ingredients)
    sauce = make_sauce(ingredients)
    assembled_pizza = assemble_pizza(dough, sauce, ingredients)

    return bake(assembled_pizza)
Python 中的软件工程原理

何时重构

命名不佳

def check(x, y=100):
    return x >= y

描述性命名

def is_boiling(temp, boiling_point=100):
    return temp >= boiling_point

过度命名

def check_if_temperature_is_above_boiling_point(
        temperature_to_check, 
        celsius_water_boiling_point=100):
    return temperature_to_check >= celsius_water_boiling_point
Python 中的软件工程原理

练习时间

Python 中的软件工程原理

Preparing Video For Download...