python是否具有某种内置功能来通知dict更新时哪些字典元素发生了变化?例如,我正在寻找这样的一些功能:
>>> a = {'a':'hamburger', 'b':'fries', 'c':'coke'} >>> b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'} >>> a.diff(b) {'c':'pepsi', 'd':'ice cream'} >>> a.update(b) >>> a {'a':'hamburger', 'b':'fries', 'c':'pepsi', 'd':'ice cream'}
我正在寻找变化值的字典,如a.diff(b)的结果所示
否,但是您可以将dict归类为更改通知。
class ObservableDict( dict ): def __init__( self, *args, **kw ): self.observers= [] super( ObservableDict, self ).__init__( *args, **kw ) def observe( self, observer ): self.observers.append( observer ) def __setitem__( self, key, value ): for o in self.observers: o.notify( self, key, self[key], value ) super( ObservableDict, self ).__setitem__( key, value ) def update( self, anotherDict ): for k in anotherDict: self[k]= anotherDict[k] class Watcher( object ): def notify( self, observable, key, old, new ): print "Change to ", observable, "at", key w= Watcher() a= ObservableDict( {'a':'hamburger', 'b':'fries', 'c':'coke'} ) a.observe( w ) b = {'b':'fries', 'c':'pepsi'} a.update( b )
请注意,此处定义的超类监视程序不会检查是否存在“真实”更改;它只是指出发生了变化。