1. 程式人生 > >【練習題】第十六章--類和函式(Think Python)

【練習題】第十六章--類和函式(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 這種用於檢查錯誤的語句與常規的條件語句在程式碼上進行區分。