【问题标题】:Python3 impossible to pass @property as decorator argumentPython3 无法将 @property 作为装饰器参数传递
【发布时间】:2020-02-23 05:19:54
【问题描述】:

我已经实现了可以接收额外参数并希望将其与类方法一起使用的装饰器。我想将@property 作为装饰器参数传递,但我得到的不是@property 结果:

<property object at 0x7f50f5195230>

这是我的装饰器:

class Decorator(object):
    def __init__(self, some_arg):
        self.func = None
        self.some_arg = some_arg

    def __get__(self, instance, owner):
        import functools
        return functools.partial(self.__call__, instance)

    def __call__(self, func):
        self.func = func
        def wrapper(*args, **kwargs):
            return self._process_sync(*args, **kwargs)
        return wrapper

    def _process_sync(self, *args, **kwargs):
        try:
            print(self.some_arg)
            return self.func(*args, **kwargs)
        except Exception as e:
            print(e)
            return None

我的测试课:

class Test(object):
    @property
    def some_data(self):
        return {'key': 'value'}

    @Decorator(some_data)
    def some_method(self):
        print('method output')
        return None

用法:

test = Test()
test.some_method()

两个问题:

  1. 如何正确传递属性以接收@property 结果而不是&lt;property object at 0x7f50f5195230&gt;
  2. 如果类属性/方法在代码下方,是否可以将它们传递给装饰器?

【问题讨论】:

  • 理解你期望传入的属性在你的装饰器中做什么有点棘手。您是否希望在调用装饰方法时查找它返回的任何值?或者你希望它以某种方式预先查找装饰器值,就在你传入它的时候?这在您的示例中并不真正相关,因为该属性始终返回相同的值,但难以预测的值会更棘手。
  • @Blckknght 我想在装饰器中使用@property 值。在原始示例中,我想传递一些异常处理程序以将它们与修饰函数一起使用。但是对于问题,我创建了一个简单的示例来了解如何正确传递@property 以获得其结果的机制(我的意思是上面示例中的 dict)而不是对象
  • @Blckknght 换句话说我不知道​​如何使用这个&lt;property object at 0x7f50f5195230&gt; 从属性接收字典

标签: python python-3.x python-decorators


【解决方案1】:

property 对象是一个描述符。要从中获取值,您需要使用适当的实例调用其__get__ 方法。在您当前的代码中确定何时执行此操作并不容易,因为您的 Decorator 对象有很多不同的角色。它既是装饰器工厂(使用@Decorator(x) 行中的参数进行初始化),又是装饰器本身(使用要装饰的函数调用)。你给了它一个__get__ 方法,但我不希望它被使用,因为Decorator 的实例永远不会被分配给一个类变量(只有从__call__ 返回的包装函数) .

无论如何,这是一个修改后的版本,Decorator 处理了描述符协议本身的几乎所有部分:

class Decorator:
    def __init__(self, arg):
        self.arg = arg      # this might be a descriptor, like a property or unbound method

    def __call__(self, func):
        self.func = func
        return self         # we still want to be the descriptor in the class

    def __get__(self, instance, owner):
        try:
            arg = self.arg.__get__(instance, owner)   # try to bind the arg to the instance
        except AttributeError: # if it doesn't work, self.arg is not a descriptor, that's OK
            arg = self.arg

        def wrapper(*args, **kwargs):   # this is our version of a bound method object
            print(arg) # do something with the bound arg here
            return self.func.__get__(instance, owner)(*args, **kwargs)

        return wrapper

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-17
    • 2021-11-21
    • 2013-03-10
    • 2013-08-21
    • 1970-01-01
    • 2018-08-24
    • 2014-10-01
    • 1970-01-01
    相关资源
    最近更新 更多