【问题标题】:Decorator / wrapper around python class attributepython类属性周围的装饰器/包装器
【发布时间】:2019-10-17 11:33:48
【问题描述】:

我正在尝试增强 Python 中的默认 @property 行为:

from functools import wraps

def MyProperty(func):
    def getter(self):
        """Enhance the property"""
        return func(self) + 1

    return property(getter)

class MyClass(object):
    def __init__(self, foo):
        self._foo = foo

    @MyProperty
    def foo(self):
        return self._foo

这一切都很好,我得到了想要的效果

A = MyClass(5)
A.foo
>>> 6

由于我是这样学习的,出于良好实践的原因,我想将 wraps 装饰器应用于包装器。但是,如果我确实将包装器写为

def MyProperty(func):
    @wraps
    def getter(self):
        """Enhance the property"""
        return func(self) + 1

    return property(getter)

我现在明白了

A = MyClass(5)
A.foo
>>> <__main__.MyClass object at 0x7f209f4aa0d0>

这不是我所期望的。有什么建议吗?

【问题讨论】:

    标签: python python-2.7 properties wrapper


    【解决方案1】:

    使用这个:

    def MyProperty(func):
    
        @wraps(func)
        def getter(self):
            """Enhance the property"""
            return func(self) + 1
    
        return property(getter)
    

    【讨论】:

      猜你喜欢
      • 2021-05-20
      • 1970-01-01
      • 1970-01-01
      • 2014-02-08
      • 1970-01-01
      • 2012-07-15
      • 2022-11-09
      • 2020-06-20
      • 2016-07-30
      相关资源
      最近更新 更多