码迷,mamicode.com
首页 > 其他好文 > 详细

一段看不懂的代码(关于描述符)

时间:2017-01-16 18:12:44      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:account   init   class   int   count()   dict   nbsp   bsp   object   

 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)
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

 

一段看不懂的代码(关于描述符)

标签:account   init   class   int   count()   dict   nbsp   bsp   object   

原文地址:http://www.cnblogs.com/wangzixuan-welcome/p/6290298.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!