关于描述符的一段代码

 1 class CallbackProperty(object):
 2     """A property that will alert observers when upon updates"""
 3 
 4     def __init__(self, default=None):
 5         self.data = dict()
 6         self.default = default
 7         self.callbacks = dict()
 8 
 9     def __get__(self, instance, owner):
10         if instance is None:
11             return self
12         return self.data.get(instance, self.default)
13 
14     def __set__(self, instance, value):
15         for callback in self.callbacks.get(instance, []):
16             # alert callback function of new value
17             callback(value)
18         self.data[instance] = value
19 
20     def add_callback(self, instance, callback):
21         """Add a new function to call everytime the descriptor within instance updates"""
22         if instance not in self.callbacks:
23             self.callbacks[instance] = []    # 如果是列表,可以进行添加和迭代操作
24         self.callbacks[instance].append(callback)   # 这里的callback存储的是函数
25 
26 class BankAccount(object):
27     balance = CallbackProperty(0)
28 
29 def low_balance_warning(value):
30     if value < 100:
31         print("You are now poor")
32 
33 ba = BankAccount()
34 BankAccount.balance.add_callback(ba, low_balance_warning)
35 
36 ba.balance = 5000
37 print("Balance is %s" % ba.balance)
38 ba.balance = 99

 

posted on 2017-01-16 17:00  wzxds02  阅读(206)  评论(0编辑  收藏  举报

导航