3

一开始,我知道 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 中有什么方法可以做到这一点吗?

4

2 回答 2

1

噢耶!:D 我找到了答案 - 有点疯狂,但工作很快。如果有人有评论或更好的解决方案,我会非常有兴趣看到它。以下代码适用于方法和函数:

# ----- test classes -----    
class Event:
    def __init__(self):
        self.funcs = []

    def bind(self, func):
        self.funcs.append(func)

    def __call__(self, *args, **kwargs):
        message = type('EventMessage', (), kwargs)
        for func in self.funcs:
            func(message)

# ----- implementation -----

class BindFunction:
    def __init__(self, func):
        self.func = func
        self.event = Event()

    def __call__(self, *args, **kwargs):
        out = self.func(*args, **kwargs)
        self.event(source=None)
        return out

    def bind(self, func):
        self.event.bind(func)

class BindMethod(BindFunction):
    def __init__(self, instance, func):
        super().__init__(func)
        self.instance = instance

    def __call__(self, *args, **kwargs):
        out = self.func(self.instance, *args, **kwargs)
        self.event(source=self.instance)
        return out

class Descriptor(BindFunction):
    methods = {}

    def __get__(self, instance, owner):
        if not instance in Descriptor.methods:
            Descriptor.methods[instance] = BindMethod(instance, self.func)
        return Descriptor.methods[instance]

def bindable(func):
    return Descriptor(func)

# ----- usage -----
class list:
    def __init__(self, seq=()):
        self.__list = [el for el in seq]

    @bindable
    def append(self, p_object):
        self.__list.append(p_object)

    def __str__(self):
        return str(self.__list)

@bindable
def x():
    print('calling x')

# ----- tests -----

def f (event):
    print('calling f')
    print('source type: %s' % type(event.source))

def g (event):
    print('calling g')
    print('source type: %s' % type(event.source))

a = list()
b = list()

a.append.bind(f)
b.append.bind(g)

a.append(5)
print(a)

b.append(6)
print(b)

print('----')

x.bind(f)
x()

和输出:

calling f
source type: <class '__main__.list'>
[5]
calling g
source type: <class '__main__.list'>
[6]
----
calling x
calling f
source type: <class 'NoneType'>

诀窍是使用 Python 的描述符来存储当前实例指针。

因此,我们能够将回调绑定到任何 python 函数。执行开销并不太大——函数执行比没有这个装饰器慢 5 - 6 倍。这种开销是由所需的函数链事件处理引起的。

When using the "proper" event implementation (using weak references), like this one: Signal slot implementation, we are getting the overhead of 20 - 25 times the base function execution, which still is good.

EDIT: According to Hyperboreus question, I updated the code to be able to read from the callback methods the source object from whic the callbacks were called. They are now accessible by event.source variable.

于 2013-01-31T03:57:59.480 回答
0

老实说,我对你的问题没有答案,只是另一个问题是返回:

猴子修补您的实例不会创建您想要的行为:

#! /usr/bin/python3.2

import types

class X:
    def __init__ (self, name): self.name = name
    def test (self): print (self.name, 'test')

def f (self): print (self.name, '!!!')

a = X ('A')
b = X ('B')

b.test = types.MethodType (f, b) #"binding"

a.test ()
b.test ()
于 2013-01-31T03:54:52.293 回答