最初は、バインドされたメソッドの属性がPython 3に存在しないことを知っています(このトピックによると:バインドされたメソッドでsetattrが失敗するのはなぜですか)
疑似「リアクティブ」Pythonフレームワークを作成しようとしています。多分私は何かが足りないのかもしれませんし、多分、私がやろうとしていることはどういうわけか実行可能であるということです。コードを見てみましょう:
from collections import defaultdict
class Event:
def __init__(self):
self.funcs = []
def bind(self, func):
self.funcs.append(func)
def __call__(self, *args, **kwargs):
for func in self.funcs:
func(*args, **kwargs)
def bindable(func):
events = defaultdict(Event)
def wrapper(self, *args, **kwargs):
func(self, *args, **kwargs)
# I'm doing it this way, because we need event PER class instance
events[self]()
def bind(func):
# Is it possible to somehow implement this method "in proper way"?
# to capture "self" somehow - it has to be implemented in other way than now,
# because now it is simple function not connected to an instance.
print ('TODO')
wrapper.bind = bind
return wrapper
class X:
# this method should be bindable - you should be able to attach callback to it
@bindable
def test(self):
print('test')
# sample usage:
def f():
print('calling f')
a = X()
b = X()
# binding callback
a.test.bind(f)
a.test() # should call f
b.test() # should NOT call f
もちろんEvent
、この例では、のようなすべてのクラスが簡略化されています。このコードを修正して機能させる方法はありますか?デコレータを使用してメソッド(関数ではありません!)をバインド可能にし、後でコールバックに「バインド」できるようにしたいだけですbindable
。このようにして、誰かがメソッドを呼び出すと、コールバックが自動的に呼び出されます。 。
Python 3でそれを行う方法はありますか?