【练习题】第十六章--类和函数(Think Python)

class Time:
    hour=0
    minute=0
    second=0

def print_time(t):
    print("%.2d:%.2d:%.2d"%(t.hour,t.minute,t.second))

def is_after(t1,t2):
    return (t1.hour,t1.minute,t1.second)>(t2.hour,t2.minute,t2.second)

纯函数:不会导致已有对象的修改;

修改器:会导致已有对象的修改。

总的来说,我还是建议你写纯函数,除非用修改器有特别显著的好处。这种模式也叫做函数式编程。

ef add_time(t1, t2):
    assert valid_time(t1) and valid_time(t2)
    seconds = time_to_int(t1) + time_to_int(t2)
    return int_to_time(seconds)

assert 语句是很有用的,可以用来区分条件语句的用途,将 assert 这种用于检查错误的语句与常规的条件语句在代码上进行区分。

猜你喜欢

转载自blog.csdn.net/qq_29567851/article/details/83589650