举个现实生活的例子,职员们趁老板不在,都在玩着自己的东西,同时观察着前台小姐姐,前台小姐姐在老板回来的时候,发布通知让各同事回到工作状态。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| class StockClerk: def __init__(self, name): self.name = name
def close_stock_software(self): print(f"{self.name} 关闭了股票软件,并开始办公")
class SleepingClerk: def __init__(self, name): self.name = name
def open_word(self): print(f"{self.name} 打开了word,并开始办公")
class Receptionist: actions = []
@classmethod def attach(cls, action): cls.actions.append(action)
@classmethod def notify(cls): print("老板回来了,各同事行动...") for actioin in cls.actions: actioin()
c1 = StockClerk('Chris') c2 = SleepingClerk('Ryan')
Receptionist.attach(c1.close_stock_software) Receptionist.attach(c2.open_word)
Receptionist.notify()
|