Skip to main content
 首页 » 编程设计

python之如何使用装饰器将函数绑定(bind)到对象实例

2024年12月31日7yjmyzz

我正在尝试将一个函数绑定(bind)到一个对象实例。例如,我有一个对象,我试图将一个函数绑定(bind)到条件属性。 问题是我想使用装饰器来做到这一点:

class Transition(object): 
    def __init__(self, enter, exit, condition=None): 
        if not isinstance(enter, State) or not isinstance(exit, State): 
            raise TypeError("Parameters should be an instance of the State class") 
        self.enter = enter 
        self.exit = exit 
        self.condition = None 
        self.effect = None 
 
    def __repr__(self): 
        print("Going from {} to {} with condition {} and effect {}".format(self.enter, self.exit, self.condition.__name__, self.effect.__name__))  
 
    def __eq__(self, other): 
        return self.enter == other.enter and self.exit == other.exit 
 
    def is_enpoint(self, endpoints): 
        """ 
        :parameter --> 'endpoints' is a tuple indicating where the transition flows(from, to)  
        :return --> boolean 
        :description --> check if the given endpoints are valid  
        """ 
        return self.enter == endpoints[0] and self.exit == endpoints[1] 

然后我将一个函数绑定(bind)到对象的实例。

@bind 
my_condition(): 
    return True 

在此之后,如果我们查看对象的实例条件属性,我们应该有一个给定函数的引用

编辑 1:

f = Transition() 
f1 = Transition() 
 
@bind(f) 
def condition1(): 
    return True 
 
@bind(f1) 
def condition2(): 
    return False 

f 实例应引用 condition1 函数,f2 实例应引用 condition2 以获取 condition 属性

请您参考如下方法:

当然,装饰器必须将要绑定(bind)到的实例作为参数获取 - 而且,如果装饰函数本身有一个参数作为绑定(bind)的实例传递,代码会更简洁too: 相当于 self 如果它被定义为一个方法。 Python 不会自动插入它,但它可能被称为 self 以便于阅读;

class Transition: 
   ... 
 
f = Transition 
 
def bind(instance): 
    def decorator(func): 
        def wrapper (*args, **kwargs): 
              return func(instance, *args, **kwargs) 
        setattr(instance, func.__name__, wrapper) 
        return wrapper 
    return decorator 
 
@bind(f) 
def condition(self, ...): 
    ... 

如果你想要一个更扁平的装饰器,你可以使用 functools.partial - 然后我也使用 functools.wraps,因为好的装饰器无论如何都应该使用它:

import functools 
 
... 
 
def bind(func, instance=None): 
    if instance is None: 
         return functools.partial(bind, instance=func) 
    @functools.wraps(func) 
    def wrapper(*args, **kw): 
         return func(instance, *args, **kw) 
    setattr(instance, func.__name__, wrapper) 
    return wrapper 

这是可行的,因为在 Python 中,当一个函数直接归因于一个实例时,它的行为与任何普通属性完全一样:Python 将检索该函数,然后调用它,不进行任何修改——不将其更改为方法,也不插入self 参数)。我们通过将实例作为装饰器代码中的非局部变量来实现这一点。