函数的观察模式与定界方法
observed的Python项目详细描述
observated允许您注册要“observate”的函数或方法 其他功能或方法:
fromobservedimportobservable_function@observable_functiondefobserved_func(arg):print("observed_func: %s"%(arg,))defobserver_func(arg):print("observer_func: %s"%(arg,))observed_func.add_observer(observer_func)observed_func('banana')>>>observed_func:banana>>>observer_func:banana
您还可以为绑定方法注册观察员:
fromobservedimportobservable_methodclassFoo:def__init__(self,name):self.name=name@observable_method()defbar(self,arg):print("Object %s invoked bar with arg='%s'"%(self.name,arg))defbaz(self,arg):print("Object %s invoked baz with arg='%s'"%(self.name,arg))defcallback(arg):print("callback was invoked with arg='%s'"%(arg,))a=Foo('a')b=Foo('b')a.bar.add_observer(b.bar)a.bar.add_observer(b.baz)a.bar.add_observer(callback)a.bar('banana')>>>Objectainvokedbarwitharg='banana'>>>Objectbinvokedbarwitharg='banana'>>>Objectbinvokedbazwitharg='banana'>>>callbackwasinvokedwitharg='banana'
您可以要求观察到的对象将自身作为第一个参数传递 每当它呼叫观察员时:
fromobservedimportobservable_function@observable_functiondefobserved_func():print("observed_func: I was called")defobserver_func(observed):print("observer_func: %s called me"%(observed.__name__,))observed_func.add_observer(observer_func,identify_observed=True)observed_func()>>>observed_func:Iwascalled>>>observer_func:observed_funccalledme
当观察到的绑定方法将自身作为观察对象传递时,请保持
请注意,您始终可以通过__self__
:
fromobservedimportobservable_methodclassFoo:def__init__(self,name):self.name=name@observable_method()defbar(self):print("Object %s invoked bar"%(self.name,))defcallback(observed):print("callback was invoked by='%s'"%(observed.__self__.name,))a=Foo('a')a.bar.add_observer(callback,identify_observed=True)a.bar()>>>Objectainvokedbar>>>callbackwasinvokedbya
值得注意的功能包括:
函数或绑定方法不能仅仅因为它是 观察其他事物。这是因为观察到的物体 不保留对观察对象的任何强引用。在cpython 这意味着当 该观察者的引用计数变为零。
observate_method decorator可用于类中的方法 它们是不可更改的类型,可用于任意数量的 每个类中的方法…
…但处理可观察方法的描述符不粘贴 它管理的实例上的任何数据。没有名字的可能 与观察到的实例发生冲突。
安装
Python包索引中存在“p> ^ {STR 1 } $ >,您可以这样做pip install observed
来安装它。或者,你可以
下载源发行版并在
分发do$ python setup.py install
新闻
有关以前版本中用户可见的更改,请参见文件新闻。
许可证
见LICENSE.txt
。
正在下载
可从 python package index at 或者通过GitHub。
文档
基本用法在这个文件的顶部有说明。进一步的例子是
在example.py
中给出。
开发
观察到的开发托管在github上。当前工作存储库 在上面的下载部分给出。