一段看不懂的代码(关于描述符)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一段看不懂的代码(关于描述符)相关的知识,希望对你有一定的参考价值。
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
以上是关于一段看不懂的代码(关于描述符)的主要内容,如果未能解决你的问题,请参考以下文章