1 classCallbackproperty (object):2 """A property that would alert observers when upon updates"""3 4 def __init__(Self, default=None):5Self.data =dict ()6Self.default =default7Self.callbacks =dict ()8 9 def __get__(self, instance, owner):Ten ifInstance isNone: One return Self A returnSelf.data.get (instance, Self.default) - - def __set__(self, instance, value): the forCallbackinchSelf.callbacks.get (instance, []): - #Alert callback function of new value - callback (value) -Self.data[instance] =value + - defAdd_callback (self, instance, callback): + """Add A new function to call everytime the descriptor within instance updates""" A ifInstance not inchself.callbacks: atSelf.callbacks[instance] = [] - Self.callbacks[instance].append (callback) - - classBankAccount (object): -Balance =callbackproperty (0) - in deflow_balance_warning (value): - ifValue < 100: to Print("You is now poor") + -BA =BankAccount () the BankAccount.balance.add_callback (BA, low_balance_warning) * $Ba.balance = 5000Panax Notoginseng Print("Balance is%s"%ba.balance) -Ba.balance = 99
A piece of code that you can't read (about descriptors)