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

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

 

以上是关于一段看不懂的代码(关于描述符)的主要内容,如果未能解决你的问题,请参考以下文章

jquery easyui 可折叠的导航菜单这段看不懂,求详解

搞笑如何写出别人看不懂自己也看不懂的代码

看不懂的 build.gradle 代码

一段程序看不懂,高手帮忙读一下

Java小白也能轻松写一个大神都看不懂的程序,绝对让人佩服

Java小白也能轻松写一个大神都看不懂的程序,绝对让人佩服