一开始,我知道 Python 3 中不存在绑定方法属性(根据本主题:Why does setattr fail on a bound method)
我正在尝试编写一个伪“反应式”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 中有什么方法可以做到这一点吗?